{"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"0.30042552947998047","kind":"field","lang":"csv","code":"0.30042552947998047"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"0.3699159622192383","kind":"field","lang":"csv","code":"0.3699159622192383"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"0.2950403690338135","kind":"field","lang":"csv","code":"0.2950403690338135"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"1.7572166919708252","kind":"field","lang":"csv","code":"1.7572166919708252"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"1.7568728923797607","kind":"field","lang":"csv","code":"1.7568728923797607"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"1.7468714714050293","kind":"field","lang":"csv","code":"1.7468714714050293"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":8,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-17-ubuntu1604-ec2/raw.csv","line":8,"symbol":"git grep (ignore)","kind":"field","lang":"csv","code":"git grep (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"0.47386884689331055","kind":"field","lang":"csv","code":"0.47386884689331055"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"0.4676964282989502","kind":"field","lang":"csv","code":"0.4676964282989502"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"0.2977464199066162","kind":"field","lang":"csv","code":"0.2977464199066162"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"0.404477596282959","kind":"field","lang":"csv","code":"0.404477596282959"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"0.29970765113830566","kind":"field","lang":"csv","code":"0.29970765113830566"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"0.2981560230255127","kind":"field","lang":"csv","code":"0.2981560230255127"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":8,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":8,"symbol":"10","kind":"field","lang":"csv","code":"10"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-20-ubuntu1604-ec2/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"0.16187143325805664","kind":"field","lang":"csv","code":"0.16187143325805664"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"0.15862464904785156","kind":"field","lang":"csv","code":"0.15862464904785156"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"0.15711188316345215","kind":"field","lang":"csv","code":"0.15711188316345215"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"0.5682125091552734","kind":"field","lang":"csv","code":"0.5682125091552734"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"0.551994800567627","kind":"field","lang":"csv","code":"0.551994800567627"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"0.5516140460968018","kind":"field","lang":"csv","code":"0.5516140460968018"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":8,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-09-22-archlinux-cheetah/raw.csv","line":8,"symbol":"git grep (ignore)","kind":"field","lang":"csv","code":"git grep (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"0.09865546226501465","kind":"field","lang":"csv","code":"0.09865546226501465"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"0.08865809440612793","kind":"field","lang":"csv","code":"0.08865809440612793"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"0.0934293270111084","kind":"field","lang":"csv","code":"0.0934293270111084"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"0.07241153717041016","kind":"field","lang":"csv","code":"0.07241153717041016"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"0.06905841827392578","kind":"field","lang":"csv","code":"0.06905841827392578"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"0.06687068939208984","kind":"field","lang":"csv","code":"0.06687068939208984"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":8,"symbol":"linux_alternates_casei","kind":"field","lang":"csv","code":"linux_alternates_casei"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"0.09452986717224121","kind":"field","lang":"csv","code":"0.09452986717224121"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"0.08666801452636719","kind":"field","lang":"csv","code":"0.08666801452636719"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"0.08859610557556152","kind":"field","lang":"csv","code":"0.08859610557556152"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"0.07011771202087402","kind":"field","lang":"csv","code":"0.07011771202087402"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"0.06441712379455566","kind":"field","lang":"csv","code":"0.06441712379455566"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"0.06532430648803711","kind":"field","lang":"csv","code":"0.06532430648803711"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":8,"symbol":"linux_alternates_casei","kind":"field","lang":"csv","code":"linux_alternates_casei"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-jemalloc/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"0.09608030319213867","kind":"field","lang":"csv","code":"0.09608030319213867"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"0.08815908432006836","kind":"field","lang":"csv","code":"0.08815908432006836"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"0.08974266052246094","kind":"field","lang":"csv","code":"0.08974266052246094"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"0.06675052642822266","kind":"field","lang":"csv","code":"0.06675052642822266"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"0.06632375717163086","kind":"field","lang":"csv","code":"0.06632375717163086"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"0.06531620025634766","kind":"field","lang":"csv","code":"0.06531620025634766"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":8,"symbol":"linux_alternates_casei","kind":"field","lang":"csv","code":"linux_alternates_casei"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-glibc-system/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"0.10048675537109375","kind":"field","lang":"csv","code":"0.10048675537109375"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"0.09462523460388184","kind":"field","lang":"csv","code":"0.09462523460388184"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"0.0931856632232666","kind":"field","lang":"csv","code":"0.0931856632232666"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"0.06952047348022461","kind":"field","lang":"csv","code":"0.06952047348022461"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"0.07045698165893555","kind":"field","lang":"csv","code":"0.07045698165893555"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"0.06589603424072266","kind":"field","lang":"csv","code":"0.06589603424072266"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":8,"symbol":"linux_alternates_casei","kind":"field","lang":"csv","code":"linux_alternates_casei"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-jemalloc/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"0.09466052055358887","kind":"field","lang":"csv","code":"0.09466052055358887"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"0.09342074394226074","kind":"field","lang":"csv","code":"0.09342074394226074"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"0.0869603157043457","kind":"field","lang":"csv","code":"0.0869603157043457"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"0.06717634201049805","kind":"field","lang":"csv","code":"0.06717634201049805"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"0.06487321853637695","kind":"field","lang":"csv","code":"0.06487321853637695"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"0.06573486328125","kind":"field","lang":"csv","code":"0.06573486328125"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":8,"symbol":"linux_alternates_casei","kind":"field","lang":"csv","code":"linux_alternates_casei"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-24-archlinux-cheetah-musl-system/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"0.09816598892211914","kind":"field","lang":"csv","code":"0.09816598892211914"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"0.08965039253234863","kind":"field","lang":"csv","code":"0.08965039253234863"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"0.09101128578186035","kind":"field","lang":"csv","code":"0.09101128578186035"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"0.07472872734069824","kind":"field","lang":"csv","code":"0.07472872734069824"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"0.07628297805786133","kind":"field","lang":"csv","code":"0.07628297805786133"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"rg (whitelist)","kind":"field","lang":"csv","code":"rg (whitelist)"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg --no-ignore -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"0.07189559936523438","kind":"field","lang":"csv","code":"0.07189559936523438"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":8,"symbol":"linux_alternates_casei","kind":"field","lang":"csv","code":"linux_alternates_casei"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2016-12-30-archlinux-cheetah/raw.csv","line":8,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"0.10186767578125","kind":"field","lang":"csv","code":"0.10186767578125"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":2,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"0.10199356079101562","kind":"field","lang":"csv","code":"0.10199356079101562"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":3,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"0.09750819206237793","kind":"field","lang":"csv","code":"0.09750819206237793"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":4,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"0.09634733200073242","kind":"field","lang":"csv","code":"0.09634733200073242"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":5,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"rg (ignore)","kind":"field","lang":"csv","code":"rg (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"rg -n ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"0.10117292404174805","kind":"field","lang":"csv","code":"0.10117292404174805"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":6,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT","kind":"field","lang":"csv","code":"ag -s ERR_SYS|PME_TURN_OFF|LINK_REQ_RST|CFG_BME_EVT"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"0.49642109870910645","kind":"field","lang":"csv","code":"0.49642109870910645"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":7,"symbol":"68","kind":"field","lang":"csv","code":"68"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":8,"symbol":"linux_alternates","kind":"field","lang":"csv","code":"linux_alternates"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":8,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2018-01-08-archlinux-cheetah/raw.csv","line":8,"symbol":"ag (ignore)","kind":"field","lang":"csv","code":"ag (ignore)"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"0.12675833702087402","kind":"field","lang":"csv","code":"0.12675833702087402"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":2,"symbol":"19","kind":"field","lang":"csv","code":"19"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"0.1196434497833252","kind":"field","lang":"csv","code":"0.1196434497833252"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":3,"symbol":"19","kind":"field","lang":"csv","code":"19"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"0.12096214294433594","kind":"field","lang":"csv","code":"0.12096214294433594"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":4,"symbol":"19","kind":"field","lang":"csv","code":"19"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"0.1257617473602295","kind":"field","lang":"csv","code":"0.1257617473602295"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":5,"symbol":"19","kind":"field","lang":"csv","code":"19"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"0.12903356552124023","kind":"field","lang":"csv","code":"0.12903356552124023"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":6,"symbol":"19","kind":"field","lang":"csv","code":"19"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"ag","kind":"field","lang":"csv","code":"ag"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"ag PM_RESUME","kind":"field","lang":"csv","code":"ag PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"0.8575565814971924","kind":"field","lang":"csv","code":"0.8575565814971924"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":7,"symbol":"19","kind":"field","lang":"csv","code":"19"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":8,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":8,"symbol":"5","kind":"field","lang":"csv","code":"5"} {"repo":"ripgrep","file":"benchsuite/runs/2020-10-14-archlinux-frink/raw.csv","line":8,"symbol":"ag","kind":"field","lang":"csv","code":"ag"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"benchmark","kind":"field","lang":"csv","code":"benchmark"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"warmup_iter","kind":"field","lang":"csv","code":"warmup_iter"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"iter","kind":"field","lang":"csv","code":"iter"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"name","kind":"field","lang":"csv","code":"name"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"command","kind":"field","lang":"csv","code":"command"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"duration","kind":"field","lang":"csv","code":"duration"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"lines","kind":"field","lang":"csv","code":"lines"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":1,"symbol":"env","kind":"field","lang":"csv","code":"env"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"0.08678817749023438","kind":"field","lang":"csv","code":"0.08678817749023438"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":2,"symbol":"39","kind":"field","lang":"csv","code":"39"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"0.08307123184204102","kind":"field","lang":"csv","code":"0.08307123184204102"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":3,"symbol":"39","kind":"field","lang":"csv","code":"39"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"rg","kind":"field","lang":"csv","code":"rg"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"rg PM_RESUME","kind":"field","lang":"csv","code":"rg PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"0.08347964286804199","kind":"field","lang":"csv","code":"0.08347964286804199"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":4,"symbol":"39","kind":"field","lang":"csv","code":"39"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"ag","kind":"field","lang":"csv","code":"ag"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"ag PM_RESUME","kind":"field","lang":"csv","code":"ag PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"0.2955434322357178","kind":"field","lang":"csv","code":"0.2955434322357178"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":5,"symbol":"39","kind":"field","lang":"csv","code":"39"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"ag","kind":"field","lang":"csv","code":"ag"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"ag PM_RESUME","kind":"field","lang":"csv","code":"ag PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"0.2954287528991699","kind":"field","lang":"csv","code":"0.2954287528991699"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":6,"symbol":"39","kind":"field","lang":"csv","code":"39"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"ag","kind":"field","lang":"csv","code":"ag"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"ag PM_RESUME","kind":"field","lang":"csv","code":"ag PM_RESUME"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"0.2938194274902344","kind":"field","lang":"csv","code":"0.2938194274902344"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":7,"symbol":"39","kind":"field","lang":"csv","code":"39"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":8,"symbol":"linux_literal_default","kind":"field","lang":"csv","code":"linux_literal_default"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":8,"symbol":"1","kind":"field","lang":"csv","code":"1"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":8,"symbol":"3","kind":"field","lang":"csv","code":"3"} {"repo":"ripgrep","file":"benchsuite/runs/2022-12-16-archlinux-duff/raw.csv","line":8,"symbol":"git grep","kind":"field","lang":"csv","code":"git grep"} {"repo":"ripgrep","file":"build.rs","line":1,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n set_git_revision_hash();\n set_windows_exe_options();\n}"} {"repo":"ripgrep","file":"build.rs","line":12,"symbol":"set_windows_exe_options","kind":"function","lang":"rust","doc":"Embed a Windows manifest and set some linker options. The main reason for this is to enable long path support on Windows. This still, I believe, requires enabling long path support in the registry. But if that's enabled, then this will let ripgrep use C:\\... style paths that are longer than 260 characters.","code":"fn set_windows_exe_options() {\n static MANIFEST: &str = \"pkg/windows/Manifest.xml\";\n\n let Ok(target_os) = std::env::var(\"CARGO_CFG_TARGET_OS\") else { return };\n let Ok(target_env) = std::env::var(\"CARGO_CFG_TARGET_ENV\") else { return };\n if !(target_os == \"windows\" && target_env == \"msvc\") {\n return;\n }\n\n let Ok(mut manifest) = std::env::current_dir() else { return };\n manifest.push(MANIFEST);\n let Some(manifest) = manifest.to_str() else { return };\n\n println!(\"cargo:rerun-if-changed={MANIFEST}\");\n // Embed the Windows application manifest file.\n println!(\"cargo:rustc-link-arg-bin=rg=/MANIFEST:EMBED\");\n println!(\"cargo:rustc-link-arg-bin=rg=/MANIFESTINPUT:{manifest}\");\n // Turn linker warnings into errors. Helps debugging, otherwise the\n // warnings get squashed (I believe).\n println!(\"cargo:rustc-link-arg-bin=rg=/WX\");\n}"} {"repo":"ripgrep","file":"build.rs","line":36,"symbol":"set_git_revision_hash","kind":"function","lang":"rust","doc":"Make the current git hash available to the build as the environment variable `RIPGREP_BUILD_GIT_HASH`.","code":"fn set_git_revision_hash() {\n use std::process::Command;\n\n let args = &[\"rev-parse\", \"--short=10\", \"HEAD\"];\n let output = Command::new(\"git\").args(args).output();\n match output {\n Ok(output) => {\n let rev =\n String::from_utf8_lossy(&output.stdout).trim().to_string();\n if rev.is_empty() {\n println!(\n \"cargo:warning=output from `git rev-parse` is empty, \\\n so skipping embedding of commit hash\"\n );\n return;\n }\n println!(\"cargo:rustc-env=RIPGREP_BUILD_GIT_HASH={rev}\");\n }\n Err(e) => {\n println!(\n \"cargo:warning=failed to run `git rev-parse`, \\\n so skipping embedding of commit hash: {e}\"\n );\n }\n }\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":9,"symbol":"cargo_out_dir","kind":"function","lang":"bash","doc":"Finds Cargo's `OUT_DIR` directory from the most recent build. This requires one parameter corresponding to the target directory to search for the build output.","code":"cargo_out_dir() {\n # This works by finding the most recent stamp file, which is produced by\n # every ripgrep build.\n target_dir=\"$1\"\n find \"$target_dir\" -name ripgrep-stamp -print0 \\\n | xargs -0 ls -t \\\n | head -n1 \\\n | xargs dirname\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":12,"symbol":"target_dir","kind":"variable","lang":"bash","doc":"This works by finding the most recent stamp file, which is produced by every ripgrep build.","code":"target_dir=\"$1\""} {"repo":"ripgrep","file":"ci/utils.sh","line":19,"symbol":"host","kind":"function","lang":"bash","code":"host() {\n case \"$TRAVIS_OS_NAME\" in\n linux)\n echo x86_64-unknown-linux-gnu\n ;;\n osx)\n echo x86_64-apple-darwin\n ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":30,"symbol":"architecture","kind":"function","lang":"bash","code":"architecture() {\n case \"$TARGET\" in\n x86_64-*)\n echo amd64\n ;;\n i686-*|i586-*|i386-*)\n echo i386\n ;;\n arm*-unknown-linux-gnueabihf)\n echo armhf\n ;;\n *)\n die \"architecture: unexpected target $TARGET\"\n ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":47,"symbol":"gcc_prefix","kind":"function","lang":"bash","code":"gcc_prefix() {\n case \"$(architecture)\" in\n armhf)\n echo arm-linux-gnueabihf-\n ;;\n *)\n return\n ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":58,"symbol":"is_musl","kind":"function","lang":"bash","code":"is_musl() {\n case \"$TARGET\" in\n *-musl) return 0 ;;\n *) return 1 ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":65,"symbol":"is_x86","kind":"function","lang":"bash","code":"is_x86() {\n case \"$(architecture)\" in\n amd64|i386) return 0 ;;\n *) return 1 ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":72,"symbol":"is_x86_64","kind":"function","lang":"bash","code":"is_x86_64() {\n case \"$(architecture)\" in\n amd64) return 0 ;;\n *) return 1 ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":79,"symbol":"is_arm","kind":"function","lang":"bash","code":"is_arm() {\n case \"$(architecture)\" in\n armhf) return 0 ;;\n *) return 1 ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":86,"symbol":"is_linux","kind":"function","lang":"bash","code":"is_linux() {\n case \"$TRAVIS_OS_NAME\" in\n linux) return 0 ;;\n *) return 1 ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":93,"symbol":"is_osx","kind":"function","lang":"bash","code":"is_osx() {\n case \"$TRAVIS_OS_NAME\" in\n osx) return 0 ;;\n *) return 1 ;;\n esac\n}"} {"repo":"ripgrep","file":"ci/utils.sh","line":100,"symbol":"builder","kind":"function","lang":"bash","code":"builder() {\n if is_musl && is_x86_64; then\n cargo install cross\n echo \"cross\"\n else\n echo \"cargo\"\n fi\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":15,"symbol":"DecompressionMatcherBuilder","kind":"type","lang":"rust","doc":"A builder for a matcher that determines which files get decompressed.","code":"pub struct DecompressionMatcherBuilder {\n /// The commands for each matching glob.\n commands: Vec,\n /// Whether to include the default matching rules.\n defaults: bool,\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":25,"symbol":"DecompressionCommand","kind":"type","lang":"rust","doc":"A representation of a single command for decompressing data out-of-process.","code":"struct DecompressionCommand {\n /// The glob that matches this command.\n glob: String,\n /// The command or binary name.\n bin: PathBuf,\n /// The arguments to invoke with the command.\n args: Vec,\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":35,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> DecompressionMatcherBuilder {\n DecompressionMatcherBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":42,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for configuring a decompression matcher.","code":"pub fn new() -> DecompressionMatcherBuilder {\n DecompressionMatcherBuilder { commands: vec![], defaults: true }\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":50,"symbol":"build","kind":"function","lang":"rust","doc":"Build a matcher for determining how to decompress files. If there was a problem compiling the matcher, then an error is returned.","code":"pub fn build(&self) -> Result {\n let defaults = if !self.defaults {\n vec![]\n } else {\n default_decompression_commands()\n };\n let mut glob_builder = GlobSetBuilder::new();\n let mut commands = vec![];\n for decomp_cmd in defaults.iter().chain(&self.commands) {\n let glob = Glob::new(&decomp_cmd.glob).map_err(|err| {\n CommandError::io(io::Error::new(io::ErrorKind::Other, err))\n })?;\n glob_builder.add(glob);\n commands.push(decomp_cmd.clone());\n }\n let globs = glob_builder.build().map_err(|err| {\n CommandError::io(io::Error::new(io::ErrorKind::Other, err))\n })?;\n Ok(DecompressionMatcher { globs, commands })\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":76,"symbol":"defaults","kind":"function","lang":"rust","doc":"When enabled, the default matching rules will be compiled into this matcher before any other associations. When disabled, only the rules explicitly given to this builder will be used. This is enabled by default.","code":"pub fn defaults(&mut self, yes: bool) -> &mut DecompressionMatcherBuilder {\n self.defaults = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":96,"symbol":"associate","kind":"function","lang":"rust","doc":"into an absolute path internally before being executed by the current platform. Notably, on Windows, this avoids a security problem where passing a relative path to `CreateProcess` will automatically search the current directory for a matching program. If the program could not be resolved, then it is silently ignored and the association is dropped. For this reason, callers should prefer `try_associate`.","code":"pub fn associate(\n &mut self,\n glob: &str,\n program: P,\n args: I,\n ) -> &mut DecompressionMatcherBuilder\n where\n P: AsRef,\n I: IntoIterator,\n A: AsRef,\n {\n let _ = self.try_associate(glob, program, args);\n self\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":125,"symbol":"try_associate","kind":"function","lang":"rust","doc":"The `program` given is resolved with respect to `PATH` and turned into an absolute path internally before being executed by the current platform. Notably, on Windows, this avoids a security problem where passing a relative path to `CreateProcess` will automatically search the current directory for a matching program. If the program could not be resolved, then an error is returned.","code":"pub fn try_associate(\n &mut self,\n glob: &str,\n program: P,\n args: I,\n ) -> Result<&mut DecompressionMatcherBuilder, CommandError>\n where\n P: AsRef,\n I: IntoIterator,\n A: AsRef,\n {\n let glob = glob.to_string();\n let bin = try_resolve_binary(Path::new(program.as_ref()))?;\n let args =\n args.into_iter().map(|a| a.as_ref().to_os_string()).collect();\n self.commands.push(DecompressionCommand { glob, bin, args });\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":147,"symbol":"DecompressionMatcher","kind":"type","lang":"rust","doc":"A matcher for determining how to decompress files.","code":"pub struct DecompressionMatcher {\n /// The set of globs to match. Each glob has a corresponding entry in\n /// `commands`. When a glob matches, the corresponding command should be\n /// used to perform out-of-process decompression.\n globs: GlobSet,\n /// The commands for each matching glob.\n commands: Vec,\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":157,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> DecompressionMatcher {\n DecompressionMatcher::new()\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":167,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new matcher with default rules. To add more matching rules, build a matcher with [`DecompressionMatcherBuilder`].","code":"pub fn new() -> DecompressionMatcher {\n DecompressionMatcherBuilder::new()\n .build()\n .expect(\"built-in matching rules should always compile\")\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":179,"symbol":"command","kind":"function","lang":"rust","doc":"Return a pre-built command based on the given file path that can decompress its contents. If no such decompressor is known, then this returns `None`. If there are multiple possible commands matching the given path, then the command added last takes precedence.","code":"pub fn command>(&self, path: P) -> Option {\n if let Some(i) = self.globs.matches(path).into_iter().next_back() {\n let decomp_cmd = &self.commands[i];\n let mut cmd = Command::new(&decomp_cmd.bin);\n cmd.args(&decomp_cmd.args);\n return Some(cmd);\n }\n None\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":191,"symbol":"has_command","kind":"function","lang":"rust","doc":"Returns true if and only if the given file path has at least one matching command to perform decompression on.","code":"pub fn has_command>(&self, path: P) -> bool {\n self.globs.is_match(path)\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":198,"symbol":"DecompressionReaderBuilder","kind":"type","lang":"rust","doc":"Configures and builds a streaming reader for decompressing data.","code":"pub struct DecompressionReaderBuilder {\n matcher: DecompressionMatcher,\n command_builder: CommandReaderBuilder,\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":205,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder with the default configuration.","code":"pub fn new() -> DecompressionReaderBuilder {\n DecompressionReaderBuilder::default()\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":221,"symbol":"build","kind":"function","lang":"rust","doc":"command, but is executing in an environment where the decompression command is not available. If the given file path could not be matched with a decompression strategy, then a passthru reader is returned that does no decompression.","code":"pub fn build>(\n &self,\n path: P,\n ) -> Result {\n let path = path.as_ref();\n let Some(mut cmd) = self.matcher.command(path) else {\n return DecompressionReader::new_passthru(path);\n };\n cmd.arg(path);\n\n match self.command_builder.build(&mut cmd) {\n Ok(cmd_reader) => Ok(DecompressionReader { rdr: Ok(cmd_reader) }),\n Err(err) => {\n log::debug!(\n \"{}: error spawning command '{:?}': {} \\\n (falling back to uncompressed reader)\",\n path.display(),\n cmd,\n err,\n );\n DecompressionReader::new_passthru(path)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":251,"symbol":"matcher","kind":"function","lang":"rust","doc":"Set the matcher to use to look up the decompression command for each file path. A set of sensible rules is enabled by default. Setting this will completely replace the current rules.","code":"pub fn matcher(\n &mut self,\n matcher: DecompressionMatcher,\n ) -> &mut DecompressionReaderBuilder {\n self.matcher = matcher;\n self\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":260,"symbol":"get_matcher","kind":"function","lang":"rust","doc":"Get the underlying matcher currently used by this builder.","code":"pub fn get_matcher(&self) -> &DecompressionMatcher {\n &self.matcher\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":276,"symbol":"async_stderr","kind":"function","lang":"rust","doc":"thread in order to read stderr. This is done so that the process being executed is never blocked from writing to stdout or stderr. If this is disabled, then it is possible for the process to fill up the stderr buffer and deadlock. This is enabled by default.","code":"pub fn async_stderr(\n &mut self,\n yes: bool,\n ) -> &mut DecompressionReaderBuilder {\n self.command_builder.async_stderr(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":332,"symbol":"DecompressionReader","kind":"type","lang":"rust","doc":"let mut rdr = DecompressionReader::new(\"/usr/share/man/man1/ls.1.gz\")?; let mut contents = vec![]; rdr.read_to_end(&mut contents)?; # Ok::<(), Box>(()) ```","code":"pub struct DecompressionReader {\n rdr: Result,\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":352,"symbol":"new","kind":"function","lang":"rust","doc":"This uses the default matching rules for determining how to decompress the given file. To change those matching rules, use [`DecompressionReaderBuilder`] and [`DecompressionMatcherBuilder`]. When creating readers for many paths. it is better to use the builder since it will amortize the cost of constructing the matcher.","code":"pub fn new>(\n path: P,\n ) -> Result {\n DecompressionReaderBuilder::new().build(path)\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":361,"symbol":"new_passthru","kind":"function","lang":"rust","doc":"Creates a new \"passthru\" decompression reader that reads from the file corresponding to the given path without doing decompression and without executing another process.","code":"fn new_passthru(path: &Path) -> Result {\n let file = File::open(path)?;\n Ok(DecompressionReader { rdr: Err(file) })\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":383,"symbol":"close","kind":"function","lang":"rust","doc":"calling `close` in this case. `close` is also called in `drop` as a last line of defense against resource leakage. Any error from the child process is then printed as a warning to stderr. This can be avoided by explicitly calling `close` before the CommandReader is dropped.","code":"pub fn close(&mut self) -> io::Result<()> {\n match self.rdr {\n Ok(ref mut rdr) => rdr.close(),\n Err(_) => Ok(()),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":392,"symbol":"read","kind":"function","lang":"rust","code":"fn read(&mut self, buf: &mut [u8]) -> io::Result {\n match self.rdr {\n Ok(ref mut rdr) => rdr.read(buf),\n Err(ref mut rdr) => rdr.read(buf),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":420,"symbol":"resolve_binary","kind":"function","lang":"rust","doc":"relative path. We permit this since it is assumed that the user has set this explicitly, and thus, desires this behavior. # Platform behavior On non-Windows, this is a no-op.","code":"pub fn resolve_binary>(\n prog: P,\n) -> Result {\n if !cfg!(windows) {\n return Ok(prog.as_ref().to_path_buf());\n }\n try_resolve_binary(prog)\n}"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":448,"symbol":"try_resolve_binary","kind":"function","lang":"rust","doc":"Note that this could still return a relative path if PATH contains a relative path. We permit this since it is assumed that the user has set this explicitly, and thus, desires this behavior. If `check_exists` is false or the path is already an absolute path this will return immediately.","code":"fn try_resolve_binary>(\n prog: P,\n) -> Result {\n use std::env;\n\n fn is_exe(path: &Path) -> bool {\n let Ok(md) = path.metadata() else { return false };\n !md.is_dir()\n }\n\n let prog = prog.as_ref();\n if prog.is_absolute() {\n return Ok(prog.to_path_buf());\n }\n let Some(syspaths) = env::var_os(\"PATH\") else {\n let msg = \"system PATH environment variable not found\";\n return Err(CommandError::io(io::Error::new(\n io::ErrorKind::Other,\n msg,\n )));\n };\n for syspath in env::split_paths(&syspaths) {\n if syspath.as_os_str().is_empty() {\n continue;\n }\n let abs_prog = syspath.join(prog);\n if is_exe(&abs_prog) {\n return Ok(abs_prog.to_path_buf());\n }\n if abs_prog.extension().is_none() {\n for extension in [\"com\", \"exe\"] {\n let abs_prog = abs_prog.with_extension(extension);\n if is_exe(&abs_prog) {\n return Ok(abs_prog.to_path_buf());\n }\n }\n }\n }\n let msg = format!(\"{}: could not find executable in PATH\", prog.di"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":453,"symbol":"is_exe","kind":"function","lang":"rust","code":"fn is_exe(path: &Path) -> bool {\n let Ok(md) = path.metadata() else { return false };\n !md.is_dir()\n }"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":490,"symbol":"default_decompression_commands","kind":"function","lang":"rust","code":"fn default_decompression_commands() -> Vec {\n const ARGS_GZIP: &[&str] = &[\"gzip\", \"-d\", \"-c\"];\n const ARGS_BZIP: &[&str] = &[\"bzip2\", \"-d\", \"-c\"];\n const ARGS_XZ: &[&str] = &[\"xz\", \"-d\", \"-c\"];\n const ARGS_LZ4: &[&str] = &[\"lz4\", \"-d\", \"-c\"];\n const ARGS_LZMA: &[&str] = &[\"xz\", \"--format=lzma\", \"-d\", \"-c\"];\n const ARGS_BROTLI: &[&str] = &[\"brotli\", \"-d\", \"-c\"];\n const ARGS_ZSTD: &[&str] = &[\"zstd\", \"-q\", \"-d\", \"-c\"];\n const ARGS_UNCOMPRESS: &[&str] = &[\"uncompress\", \"-c\"];\n\n fn add(glob: &str, args: &[&str], cmds: &mut Vec) {\n let bin = match resolve_binary(Path::new(args[0])) {\n Ok(bin) => bin,\n Err(err) => {\n log::debug!(\"{}\", err);\n return;\n }\n };\n cmds.push(DecompressionCommand {\n glob: glob.to_string(),\n bin,\n args: args\n .iter()\n .skip(1)\n .map(|s| OsStr::new(s).to_os_string())\n .collect(),\n });\n }\n let mut cmds = vec![];\n add(\"*.gz\", ARGS_GZIP, &mut cmds);\n add(\"*.tgz\", ARGS_GZIP, &mut cmds);\n add(\"*.bz2\", AR"} {"repo":"ripgrep","file":"crates/cli/src/decompress.rs","line":500,"symbol":"add","kind":"function","lang":"rust","code":"fn add(glob: &str, args: &[&str], cmds: &mut Vec) {\n let bin = match resolve_binary(Path::new(args[0])) {\n Ok(bin) => bin,\n Err(err) => {\n log::debug!(\"{}\", err);\n return;\n }\n };\n cmds.push(DecompressionCommand {\n glob: glob.to_string(),\n bin,\n args: args\n .iter()\n .skip(1)\n .map(|s| OsStr::new(s).to_os_string())\n .collect(),\n });\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":26,"symbol":"escape","kind":"function","lang":"rust","doc":"``` use grep_cli::escape; assert_eq!(r\"foo\\nbar\\xFFbaz\", escape(b\"foo\\nbar\\xFFbaz\")); ```","code":"pub fn escape(bytes: &[u8]) -> String {\n bytes.escape_bytes().to_string()\n}"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":33,"symbol":"escape_os","kind":"function","lang":"rust","doc":"Escapes an OS string into a human readable string. This is like [`escape`], but accepts an OS string.","code":"pub fn escape_os(string: &OsStr) -> String {\n escape(Vec::from_os_str_lossy(string).as_bytes())\n}"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":67,"symbol":"unescape","kind":"function","lang":"rust","doc":"``` use grep_cli::unescape; assert_eq!(&b\"foo\\nbar\\xFFbaz\"[..], &*unescape(r\"foo\\nbar\\xFFbaz\")); ```","code":"pub fn unescape(s: &str) -> Vec {\n Vec::unescape_bytes(s)\n}"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":77,"symbol":"unescape_os","kind":"function","lang":"rust","doc":"Unescapes an OS string. This is like [`unescape`], but accepts an OS string. Note that this first lossily decodes the given OS string as UTF-8. That is, an escaped string (the thing given) should be valid UTF-8.","code":"pub fn unescape_os(string: &OsStr) -> Vec {\n unescape(&string.to_string_lossy())\n}"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":85,"symbol":"b","kind":"function","lang":"rust","code":"fn b(bytes: &'static [u8]) -> Vec {\n bytes.to_vec()\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":90,"symbol":"empty","kind":"function","lang":"rust","code":"fn empty() {\n assert_eq!(b(b\"\"), unescape(r\"\"));\n assert_eq!(r\"\", escape(b\"\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":96,"symbol":"backslash","kind":"function","lang":"rust","code":"fn backslash() {\n assert_eq!(b(b\"\\\\\"), unescape(r\"\\\\\"));\n assert_eq!(r\"\\\\\", escape(b\"\\\\\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":102,"symbol":"nul","kind":"function","lang":"rust","code":"fn nul() {\n assert_eq!(b(b\"\\x00\"), unescape(r\"\\x00\"));\n assert_eq!(b(b\"\\x00\"), unescape(r\"\\0\"));\n assert_eq!(r\"\\0\", escape(b\"\\x00\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":109,"symbol":"nl","kind":"function","lang":"rust","code":"fn nl() {\n assert_eq!(b(b\"\\n\"), unescape(r\"\\n\"));\n assert_eq!(r\"\\n\", escape(b\"\\n\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":115,"symbol":"tab","kind":"function","lang":"rust","code":"fn tab() {\n assert_eq!(b(b\"\\t\"), unescape(r\"\\t\"));\n assert_eq!(r\"\\t\", escape(b\"\\t\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":121,"symbol":"carriage","kind":"function","lang":"rust","code":"fn carriage() {\n assert_eq!(b(b\"\\r\"), unescape(r\"\\r\"));\n assert_eq!(r\"\\r\", escape(b\"\\r\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":127,"symbol":"nothing_simple","kind":"function","lang":"rust","code":"fn nothing_simple() {\n assert_eq!(b(b\"\\\\a\"), unescape(r\"\\a\"));\n assert_eq!(b(b\"\\\\a\"), unescape(r\"\\\\a\"));\n assert_eq!(r\"\\\\a\", escape(b\"\\\\a\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":134,"symbol":"nothing_hex0","kind":"function","lang":"rust","code":"fn nothing_hex0() {\n assert_eq!(b(b\"\\\\x\"), unescape(r\"\\x\"));\n assert_eq!(b(b\"\\\\x\"), unescape(r\"\\\\x\"));\n assert_eq!(r\"\\\\x\", escape(b\"\\\\x\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":141,"symbol":"nothing_hex1","kind":"function","lang":"rust","code":"fn nothing_hex1() {\n assert_eq!(b(b\"\\\\xz\"), unescape(r\"\\xz\"));\n assert_eq!(b(b\"\\\\xz\"), unescape(r\"\\\\xz\"));\n assert_eq!(r\"\\\\xz\", escape(b\"\\\\xz\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":148,"symbol":"nothing_hex2","kind":"function","lang":"rust","code":"fn nothing_hex2() {\n assert_eq!(b(b\"\\\\xzz\"), unescape(r\"\\xzz\"));\n assert_eq!(b(b\"\\\\xzz\"), unescape(r\"\\\\xzz\"));\n assert_eq!(r\"\\\\xzz\", escape(b\"\\\\xzz\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/escape.rs","line":155,"symbol":"invalid_utf8","kind":"function","lang":"rust","code":"fn invalid_utf8() {\n assert_eq!(r\"\\xFF\", escape(b\"\\xFF\"));\n assert_eq!(r\"a\\xFFb\", escape(b\"a\\xFFb\"));\n }"} {"repo":"ripgrep","file":"crates/cli/src/hostname.rs","line":16,"symbol":"hostname","kind":"function","lang":"rust","doc":"On Windows, this currently uses the \"physical DNS hostname\" computer name. This may change in the future. On Unix, this returns the result of the `gethostname` function from the `libc` linked into the program.","code":"pub fn hostname() -> io::Result {\n #[cfg(windows)]\n {\n use winapi_util::sysinfo::{ComputerNameKind, get_computer_name};\n get_computer_name(ComputerNameKind::PhysicalDnsHostname)\n }\n #[cfg(unix)]\n {\n gethostname()\n }\n #[cfg(not(any(windows, unix)))]\n {\n Err(io::Error::new(\n io::ErrorKind::Other,\n \"hostname could not be found on unsupported platform\",\n ))\n }\n}"} {"repo":"ripgrep","file":"crates/cli/src/hostname.rs","line":36,"symbol":"gethostname","kind":"function","lang":"rust","code":"fn gethostname() -> io::Result {\n use std::os::unix::ffi::OsStringExt;\n\n // SAFETY: There don't appear to be any safety requirements for calling\n // sysconf.\n let limit = unsafe { libc::sysconf(libc::_SC_HOST_NAME_MAX) };\n if limit == -1 {\n // It is in theory possible for sysconf to return -1 for a limit but\n // *not* set errno, in which case, io::Error::last_os_error is\n // indeterminate. But untangling that is super annoying because std\n // doesn't expose any unix-specific APIs for inspecting the errno. (We\n // could do it ourselves, but it just doesn't seem worth doing?)\n return Err(io::Error::last_os_error());\n }\n let Ok(maxlen) = usize::try_from(limit) else {\n let msg = format!(\"host name max limit ({}) overflowed usize\", limit);\n return Err(io::Error::new(io::ErrorKind::Other, msg));\n };\n // maxlen here includes the NUL terminator.\n let mut buf = vec![0; maxlen];\n // SAFETY: The pointer we give is valid as it is derived directly from a\n // Vec. Similarly, `maxlen` is the length of our Vec, and is thus valid\n // to write to.\n let rc = unsafe {\n libc::gethostname(b"} {"repo":"ripgrep","file":"crates/cli/src/hostname.rs","line":82,"symbol":"print_hostname","kind":"function","lang":"rust","code":"fn print_hostname() {\n println!(\"{:?}\", hostname().unwrap());\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":6,"symbol":"ParseSizeError","kind":"type","lang":"rust","doc":"An error that occurs when parsing a human readable size description. This error provides an end user friendly message describing why the description couldn't be parsed and what the expected format is.","code":"pub struct ParseSizeError {\n original: String,\n kind: ParseSizeErrorKind,\n}"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":12,"symbol":"ParseSizeErrorKind","kind":"type","lang":"rust","code":"enum ParseSizeErrorKind {\n InvalidFormat,\n InvalidInt(std::num::ParseIntError),\n Overflow,\n}"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":19,"symbol":"format","kind":"function","lang":"rust","code":"fn format(original: &str) -> ParseSizeError {\n ParseSizeError {\n original: original.to_string(),\n kind: ParseSizeErrorKind::InvalidFormat,\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":26,"symbol":"int","kind":"function","lang":"rust","code":"fn int(original: &str, err: std::num::ParseIntError) -> ParseSizeError {\n ParseSizeError {\n original: original.to_string(),\n kind: ParseSizeErrorKind::InvalidInt(err),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":33,"symbol":"overflow","kind":"function","lang":"rust","code":"fn overflow(original: &str) -> ParseSizeError {\n ParseSizeError {\n original: original.to_string(),\n kind: ParseSizeErrorKind::Overflow,\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":44,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n use self::ParseSizeErrorKind::*;\n\n match self.kind {\n InvalidFormat => write!(\n f,\n \"invalid format for size '{}', which should be a non-empty \\\n sequence of digits followed by an optional 'K', 'M' or 'G' \\\n suffix\",\n self.original\n ),\n InvalidInt(ref err) => write!(\n f,\n \"invalid integer found in size '{}': {}\",\n self.original, err\n ),\n Overflow => write!(f, \"size too big in '{}'\", self.original),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":66,"symbol":"from","kind":"function","lang":"rust","code":"fn from(size_err: ParseSizeError) -> std::io::Error {\n std::io::Error::new(std::io::ErrorKind::Other, size_err)\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":79,"symbol":"parse_human_readable_size","kind":"function","lang":"rust","doc":"Supported size suffixes are `K` (for kilobyte), `M` (for megabyte) and `G` (for gigabyte). If a size suffix is missing, then the size is interpreted as bytes. If the size is too big to fit into a `u64`, then this returns an error. Additional suffixes may be added over time.","code":"pub fn parse_human_readable_size(size: &str) -> Result {\n let digits_end =\n size.as_bytes().iter().take_while(|&b| b.is_ascii_digit()).count();\n let digits = &size[..digits_end];\n if digits.is_empty() {\n return Err(ParseSizeError::format(size));\n }\n let value =\n digits.parse::().map_err(|e| ParseSizeError::int(size, e))?;\n\n let suffix = &size[digits_end..];\n if suffix.is_empty() {\n return Ok(value);\n }\n let bytes = match suffix {\n \"K\" => value.checked_mul(1 << 10),\n \"M\" => value.checked_mul(1 << 20),\n \"G\" => value.checked_mul(1 << 30),\n _ => return Err(ParseSizeError::format(size)),\n };\n bytes.ok_or_else(|| ParseSizeError::overflow(size))\n}"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":107,"symbol":"suffix_none","kind":"function","lang":"rust","code":"fn suffix_none() {\n let x = parse_human_readable_size(\"123\").unwrap();\n assert_eq!(123, x);\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":113,"symbol":"suffix_k","kind":"function","lang":"rust","code":"fn suffix_k() {\n let x = parse_human_readable_size(\"123K\").unwrap();\n assert_eq!(123 * (1 << 10), x);\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":119,"symbol":"suffix_m","kind":"function","lang":"rust","code":"fn suffix_m() {\n let x = parse_human_readable_size(\"123M\").unwrap();\n assert_eq!(123 * (1 << 20), x);\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":125,"symbol":"suffix_g","kind":"function","lang":"rust","code":"fn suffix_g() {\n let x = parse_human_readable_size(\"123G\").unwrap();\n assert_eq!(123 * (1 << 30), x);\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":131,"symbol":"invalid_empty","kind":"function","lang":"rust","code":"fn invalid_empty() {\n assert!(parse_human_readable_size(\"\").is_err());\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":136,"symbol":"invalid_non_digit","kind":"function","lang":"rust","code":"fn invalid_non_digit() {\n assert!(parse_human_readable_size(\"a\").is_err());\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":141,"symbol":"invalid_overflow","kind":"function","lang":"rust","code":"fn invalid_overflow() {\n assert!(parse_human_readable_size(\"9999999999999999G\").is_err());\n }"} {"repo":"ripgrep","file":"crates/cli/src/human.rs","line":146,"symbol":"invalid_suffix","kind":"function","lang":"rust","code":"fn invalid_suffix() {\n assert!(parse_human_readable_size(\"123T\").is_err());\n }"} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":170,"symbol":"is_readable_stdin","kind":"function","lang":"rust","doc":"have this return `false` and thus potentially lead to ignoring the user's stdin data. While not ideal, this is perhaps better than falsely assuming stdin is readable, which would result in blocking forever on reading stdin. Regardless, commands should always provide explicit fallbacks to override behavior. For example, `rg foo -` will explicitly search stdin and `rg foo ./` will explicitly search the current working directory.","code":"pub fn is_readable_stdin() -> bool {\n use std::io::IsTerminal;\n\n #[cfg(unix)]\n fn imp() -> bool {\n use std::{\n fs::File,\n os::{fd::AsFd, unix::fs::FileTypeExt},\n };\n\n let stdin = std::io::stdin();\n let fd = match stdin.as_fd().try_clone_to_owned() {\n Ok(fd) => fd,\n Err(err) => {\n log::debug!(\n \"for heuristic stdin detection on Unix, \\\n could not clone stdin file descriptor \\\n (thus assuming stdin is not readable): {err}\",\n );\n return false;\n }\n };\n let file = File::from(fd);\n let md = match file.metadata() {\n Ok(md) => md,\n Err(err) => {\n log::debug!(\n \"for heuristic stdin detection on Unix, \\\n could not get file metadata for stdin \\\n (thus assuming stdin is not readable): {err}\",\n );\n return false;\n }\n };\n let ft = md.file_type();\n let is_file = ft.is_file();\n let is_fifo = ft.is_fifo();\n let is_soc"} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":174,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp() -> bool {\n use std::{\n fs::File,\n os::{fd::AsFd, unix::fs::FileTypeExt},\n };\n\n let stdin = std::io::stdin();\n let fd = match stdin.as_fd().try_clone_to_owned() {\n Ok(fd) => fd,\n Err(err) => {\n log::debug!(\n \"for heuristic stdin detection on Unix, \\\n could not clone stdin file descriptor \\\n (thus assuming stdin is not readable): {err}\",\n );\n return false;\n }\n };\n let file = File::from(fd);\n let md = match file.metadata() {\n Ok(md) => md,\n Err(err) => {\n log::debug!(\n \"for heuristic stdin detection on Unix, \\\n could not get file metadata for stdin \\\n (thus assuming stdin is not readable): {err}\",\n );\n return false;\n }\n };\n let ft = md.file_type();\n let is_file = ft.is_file();\n let is_fifo = ft.is_fifo();\n let is_socket = ft.is_socket();\n let is_readable = is_file || is_fifo || is_socket;\n "} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":219,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp() -> bool {\n let stdin = winapi_util::HandleRef::stdin();\n let typ = match winapi_util::file::typ(stdin) {\n Ok(typ) => typ,\n Err(err) => {\n log::debug!(\n \"for heuristic stdin detection on Windows, \\\n could not get file type of stdin \\\n (thus assuming stdin is not readable): {err}\",\n );\n return false;\n }\n };\n let is_disk = typ.is_disk();\n let is_pipe = typ.is_pipe();\n let is_readable = is_disk || is_pipe;\n log::debug!(\n \"for heuristic stdin detection on Windows, \\\n found that is_disk={is_disk} and is_pipe={is_pipe}, \\\n and thus concluded that is_stdin_readable={is_readable}\",\n );\n is_readable\n }"} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":244,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp() -> bool {\n log::debug!(\"on non-{{Unix,Windows}}, assuming stdin is not readable\");\n false\n }"} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":260,"symbol":"is_tty_stdin","kind":"function","lang":"rust","doc":"or a console. Note that this is now just a wrapper around [`std::io::IsTerminal`](https://doc.rust-lang.org/std/io/trait.IsTerminal.html). Callers should prefer using the `IsTerminal` trait directly. This routine is deprecated and will be removed in the next semver incompatible release.","code":"pub fn is_tty_stdin() -> bool {\n use std::io::IsTerminal;\n std::io::stdin().is_terminal()\n}"} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":279,"symbol":"is_tty_stdout","kind":"function","lang":"rust","doc":"redirected, but will condensed output when printing to a tty. Note that this is now just a wrapper around [`std::io::IsTerminal`](https://doc.rust-lang.org/std/io/trait.IsTerminal.html). Callers should prefer using the `IsTerminal` trait directly. This routine is deprecated and will be removed in the next semver incompatible release.","code":"pub fn is_tty_stdout() -> bool {\n use std::io::IsTerminal;\n std::io::stdout().is_terminal()\n}"} {"repo":"ripgrep","file":"crates/cli/src/lib.rs","line":292,"symbol":"is_tty_stderr","kind":"function","lang":"rust","doc":"or a console. Note that this is now just a wrapper around [`std::io::IsTerminal`](https://doc.rust-lang.org/std/io/trait.IsTerminal.html). Callers should prefer using the `IsTerminal` trait directly. This routine is deprecated and will be removed in the next semver incompatible release.","code":"pub fn is_tty_stderr() -> bool {\n use std::io::IsTerminal;\n std::io::stderr().is_terminal()\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":12,"symbol":"InvalidPatternError","kind":"type","lang":"rust","doc":"An error that occurs when a pattern could not be converted to valid UTF-8. The purpose of this error is to give a more targeted failure mode for patterns written by end users that are not valid UTF-8.","code":"pub struct InvalidPatternError {\n original: String,\n valid_up_to: usize,\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":20,"symbol":"valid_up_to","kind":"function","lang":"rust","doc":"Returns the index in the given string up to which valid UTF-8 was verified.","code":"pub fn valid_up_to(&self) -> usize {\n self.valid_up_to\n }"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":28,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(\n f,\n \"found invalid UTF-8 in pattern at byte offset {}: {} \\\n (disable Unicode mode and use hex escape sequences to match \\\n arbitrary bytes in a pattern, e.g., '(?-u)\\\\xFF')\",\n self.valid_up_to, self.original,\n )\n }"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":40,"symbol":"from","kind":"function","lang":"rust","code":"fn from(paterr: InvalidPatternError) -> io::Error {\n io::Error::new(io::ErrorKind::Other, paterr)\n }"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":51,"symbol":"pattern_from_os","kind":"function","lang":"rust","doc":"Convert an OS string into a regular expression pattern. This conversion fails if the given pattern is not valid UTF-8, in which case, a targeted error with more information about where the invalid UTF-8 occurs is given. The error also suggests the use of hex escape sequences, which are supported by many regex engines.","code":"pub fn pattern_from_os(pattern: &OsStr) -> Result<&str, InvalidPatternError> {\n pattern.to_str().ok_or_else(|| {\n let valid_up_to = pattern\n .to_string_lossy()\n .find('\\u{FFFD}')\n .expect(\"a Unicode replacement codepoint for invalid UTF-8\");\n InvalidPatternError { original: escape_os(pattern), valid_up_to }\n })\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":67,"symbol":"pattern_from_bytes","kind":"function","lang":"rust","doc":"Convert arbitrary bytes into a regular expression pattern. This conversion fails if the given pattern is not valid UTF-8, in which case, a targeted error with more information about where the invalid UTF-8 occurs is given. The error also suggests the use of hex escape sequences, which are supported by many regex engines.","code":"pub fn pattern_from_bytes(\n pattern: &[u8],\n) -> Result<&str, InvalidPatternError> {\n std::str::from_utf8(pattern).map_err(|err| InvalidPatternError {\n original: escape(pattern),\n valid_up_to: err.valid_up_to(),\n })\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":82,"symbol":"patterns_from_path","kind":"function","lang":"rust","doc":"Read patterns from a file path, one per line. If there was a problem reading or if any of the patterns contain invalid UTF-8, then an error is returned. If there was a problem with a specific pattern, then the error message will include the line number and the file path.","code":"pub fn patterns_from_path>(path: P) -> io::Result> {\n let path = path.as_ref();\n let file = std::fs::File::open(path).map_err(|err| {\n io::Error::new(\n io::ErrorKind::Other,\n format!(\"{}: {}\", path.display(), err),\n )\n })?;\n patterns_from_reader(file).map_err(|err| {\n io::Error::new(\n io::ErrorKind::Other,\n format!(\"{}:{}\", path.display(), err),\n )\n })\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":104,"symbol":"patterns_from_stdin","kind":"function","lang":"rust","doc":"Read patterns from stdin, one per line. If there was a problem reading or if any of the patterns contain invalid UTF-8, then an error is returned. If there was a problem with a specific pattern, then the error message will include the line number and the fact that it came from stdin.","code":"pub fn patterns_from_stdin() -> io::Result> {\n let stdin = io::stdin();\n let locked = stdin.lock();\n patterns_from_reader(locked).map_err(|err| {\n io::Error::new(io::ErrorKind::Other, format!(\":{}\", err))\n })\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":141,"symbol":"patterns_from_reader","kind":"function","lang":"rust","doc":"r\"foo\", r\"bar\\s+foo\", r\"[a-z]{3}\", ]); # Ok::<(), Box>(()) ```","code":"pub fn patterns_from_reader(rdr: R) -> io::Result> {\n let mut patterns = vec![];\n let mut line_number = 0;\n io::BufReader::new(rdr).for_byte_line(|line| {\n line_number += 1;\n match pattern_from_bytes(line) {\n Ok(pattern) => {\n patterns.push(pattern.to_string());\n Ok(true)\n }\n Err(err) => Err(io::Error::new(\n io::ErrorKind::Other,\n format!(\"{}: {}\", line_number, err),\n )),\n }\n })?;\n Ok(patterns)\n}"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":165,"symbol":"bytes","kind":"function","lang":"rust","code":"fn bytes() {\n let pat = b\"abc\\xFFxyz\";\n let err = pattern_from_bytes(pat).unwrap_err();\n assert_eq!(3, err.valid_up_to());\n }"} {"repo":"ripgrep","file":"crates/cli/src/pattern.rs","line":173,"symbol":"os","kind":"function","lang":"rust","code":"fn os() {\n use std::ffi::OsStr;\n use std::os::unix::ffi::OsStrExt;\n\n let pat = OsStr::from_bytes(b\"abc\\xFFxyz\");\n let err = pattern_from_os(pat).unwrap_err();\n assert_eq!(3, err.valid_up_to());\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":11,"symbol":"CommandError","kind":"type","lang":"rust","doc":"An error that can occur while running a command and reading its output. This error can be seamlessly converted to an `io::Error` via a `From` implementation.","code":"pub struct CommandError {\n kind: CommandErrorKind,\n}"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":16,"symbol":"CommandErrorKind","kind":"type","lang":"rust","code":"enum CommandErrorKind {\n Io(io::Error),\n Stderr(Vec),\n}"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":23,"symbol":"io","kind":"function","lang":"rust","doc":"Create an error from an I/O error.","code":"pub(crate) fn io(ioerr: io::Error) -> CommandError {\n CommandError { kind: CommandErrorKind::Io(ioerr) }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":28,"symbol":"stderr","kind":"function","lang":"rust","doc":"Create an error from the contents of stderr (which may be empty).","code":"pub(crate) fn stderr(bytes: Vec) -> CommandError {\n CommandError { kind: CommandErrorKind::Stderr(bytes) }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":33,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if and only if this error has empty data from stderr.","code":"pub(crate) fn is_empty(&self) -> bool {\n match self.kind {\n CommandErrorKind::Stderr(ref bytes) => bytes.is_empty(),\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":44,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self.kind {\n CommandErrorKind::Io(ref e) => e.fmt(f),\n CommandErrorKind::Stderr(ref bytes) => {\n let msg = String::from_utf8_lossy(bytes);\n if msg.trim().is_empty() {\n write!(f, \"\")\n } else {\n let div = \"-\".repeat(79);\n write!(\n f,\n \"\\n{div}\\n{msg}\\n{div}\",\n div = div,\n msg = msg.trim()\n )\n }\n }\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":66,"symbol":"from","kind":"function","lang":"rust","code":"fn from(ioerr: io::Error) -> CommandError {\n CommandError { kind: CommandErrorKind::Io(ioerr) }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":72,"symbol":"from","kind":"function","lang":"rust","code":"fn from(cmderr: CommandError) -> io::Error {\n match cmderr.kind {\n CommandErrorKind::Io(ioerr) => ioerr,\n CommandErrorKind::Stderr(_) => {\n io::Error::new(io::ErrorKind::Other, cmderr)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":84,"symbol":"CommandReaderBuilder","kind":"type","lang":"rust","doc":"Configures and builds a streaming reader for process output.","code":"pub struct CommandReaderBuilder {\n async_stderr: bool,\n}"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":90,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder with the default configuration.","code":"pub fn new() -> CommandReaderBuilder {\n CommandReaderBuilder::default()\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":104,"symbol":"build","kind":"function","lang":"rust","doc":"current working directory. Settings such as the stdout and stderr (but not stdin) pipes will be overridden so that they can be controlled by the reader. If there was a problem spawning the given command, then its error is returned.","code":"pub fn build(\n &self,\n command: &mut process::Command,\n ) -> Result {\n let mut child = command\n .stdout(process::Stdio::piped())\n .stderr(process::Stdio::piped())\n .spawn()?;\n let stderr = if self.async_stderr {\n StderrReader::r#async(child.stderr.take().unwrap())\n } else {\n StderrReader::sync(child.stderr.take().unwrap())\n };\n Ok(CommandReader { child, stderr, eof: false })\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":132,"symbol":"async_stderr","kind":"function","lang":"rust","doc":"thread in order to read stderr. This is done so that the process being executed is never blocked from writing to stdout or stderr. If this is disabled, then it is possible for the process to fill up the stderr buffer and deadlock. This is enabled by default.","code":"pub fn async_stderr(&mut self, yes: bool) -> &mut CommandReaderBuilder {\n self.async_stderr = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":171,"symbol":"CommandReader","kind":"type","lang":"rust","doc":"let mut rdr = CommandReader::new(&mut cmd)?; let mut contents = vec![]; rdr.read_to_end(&mut contents)?; # Ok::<(), Box>(()) ```","code":"pub struct CommandReader {\n child: process::Child,\n stderr: StderrReader,\n /// This is set to true once 'read' returns zero bytes. When this isn't\n /// set and we close the reader, then we anticipate a pipe error when\n /// reaping the child process and silence it.\n eof: bool,\n}"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":195,"symbol":"new","kind":"function","lang":"rust","doc":"If there was a problem spawning the given command, then its error is returned. If the caller requires additional configuration for the reader returned, then use [`CommandReaderBuilder`].","code":"pub fn new(\n cmd: &mut process::Command,\n ) -> Result {\n CommandReaderBuilder::new().build(cmd)\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":218,"symbol":"close","kind":"function","lang":"rust","doc":"calling `close` in this case. `close` is also called in `drop` as a last line of defense against resource leakage. Any error from the child process is then printed as a warning to stderr. This can be avoided by explicitly calling `close` before the CommandReader is dropped.","code":"pub fn close(&mut self) -> io::Result<()> {\n // Dropping stdout closes the underlying file descriptor, which should\n // cause a well-behaved child process to exit. If child.stdout is None\n // we assume that close() has already been called and do nothing.\n let stdout = match self.child.stdout.take() {\n None => return Ok(()),\n Some(stdout) => stdout,\n };\n drop(stdout);\n if self.child.wait()?.success() {\n Ok(())\n } else {\n let err = self.stderr.read_to_end();\n // In the specific case where we haven't consumed the full data\n // from the child process, then closing stdout above results in\n // a pipe signal being thrown in most cases. But I don't think\n // there is any reliable and portable way of detecting it. Instead,\n // if we know we haven't hit EOF (so we anticipate a broken pipe\n // error) and if stderr otherwise doesn't have anything on it, then\n // we assume total success.\n if !self.eof && err.is_empty() {\n return Ok(());\n }\n Err(io::Error::from(err))\n "} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":247,"symbol":"drop","kind":"function","lang":"rust","code":"fn drop(&mut self) {\n if let Err(error) = self.close() {\n log::warn!(\"{}\", error);\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":255,"symbol":"read","kind":"function","lang":"rust","code":"fn read(&mut self, buf: &mut [u8]) -> io::Result {\n let stdout = match self.child.stdout {\n None => return Ok(0),\n Some(ref mut stdout) => stdout,\n };\n let nread = stdout.read(buf)?;\n if nread == 0 {\n self.eof = true;\n self.close().map(|_| 0)\n } else {\n Ok(nread)\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":273,"symbol":"StderrReader","kind":"type","lang":"rust","doc":"A reader that encapsulates the asynchronous or synchronous reading of stderr.","code":"enum StderrReader {\n Async(Option>),\n Sync(process::ChildStderr),\n}"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":280,"symbol":"r#async","kind":"function","lang":"rust","doc":"Create a reader for stderr that reads contents asynchronously.","code":"fn r#async(mut stderr: process::ChildStderr) -> StderrReader {\n let handle =\n std::thread::spawn(move || stderr_to_command_error(&mut stderr));\n StderrReader::Async(Some(handle))\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":287,"symbol":"sync","kind":"function","lang":"rust","doc":"Create a reader for stderr that reads contents synchronously.","code":"fn sync(stderr: process::ChildStderr) -> StderrReader {\n StderrReader::Sync(stderr)\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":295,"symbol":"read_to_end","kind":"function","lang":"rust","doc":"Consumes all of stderr on to the heap and returns it as an error. If there was a problem reading stderr itself, then this returns an I/O command error.","code":"fn read_to_end(&mut self) -> CommandError {\n match *self {\n StderrReader::Async(ref mut handle) => {\n let handle = handle\n .take()\n .expect(\"read_to_end cannot be called more than once\");\n handle.join().expect(\"stderr reading thread does not panic\")\n }\n StderrReader::Sync(ref mut stderr) => {\n stderr_to_command_error(stderr)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/process.rs","line":310,"symbol":"stderr_to_command_error","kind":"function","lang":"rust","code":"fn stderr_to_command_error(stderr: &mut process::ChildStderr) -> CommandError {\n let mut bytes = vec![];\n match stderr.read_to_end(&mut bytes) {\n Ok(_) => CommandError::stderr(bytes),\n Err(err) => CommandError::io(err),\n }\n}"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":7,"symbol":"StandardStream","kind":"type","lang":"rust","doc":"A writer that supports coloring with either line or block buffering.","code":"pub struct StandardStream(StandardStreamKind);"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":23,"symbol":"stdout","kind":"function","lang":"rust","doc":"If you need more fine grained control over the buffering mode, then use one of `stdout_buffered_line` or `stdout_buffered_block`. The color choice given is passed along to the underlying writer. To completely disable colors in all cases, use `ColorChoice::Never`.","code":"pub fn stdout(color_choice: termcolor::ColorChoice) -> StandardStream {\n if std::io::stdout().is_terminal() {\n stdout_buffered_line(color_choice)\n } else {\n stdout_buffered_block(color_choice)\n }\n}"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":39,"symbol":"stdout_buffered_line","kind":"function","lang":"rust","doc":"This writer is useful when printing results directly to a tty such that users see output as soon as it's written. The downside of this approach is that it can be slower, especially when there is a lot of output. You might consider using [`stdout`] instead, which chooses the buffering strategy automatically based on whether stdout is connected to a tty.","code":"pub fn stdout_buffered_line(\n color_choice: termcolor::ColorChoice,\n) -> StandardStream {\n let out = termcolor::StandardStream::stdout(color_choice);\n StandardStream(StandardStreamKind::LineBuffered(out))\n}"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":54,"symbol":"stdout_buffered_block","kind":"function","lang":"rust","doc":"This writer is useful when printing results to a file since it amortizes the cost of writing data. The downside of this approach is that it can increase the latency of display output when writing to a tty. You might consider using [`stdout`] instead, which chooses the buffering strategy automatically based on whether stdout is connected to a tty.","code":"pub fn stdout_buffered_block(\n color_choice: termcolor::ColorChoice,\n) -> StandardStream {\n let out = termcolor::BufferedStandardStream::stdout(color_choice);\n StandardStream(StandardStreamKind::BlockBuffered(out))\n}"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":62,"symbol":"StandardStreamKind","kind":"type","lang":"rust","code":"enum StandardStreamKind {\n LineBuffered(termcolor::StandardStream),\n BlockBuffered(termcolor::BufferedStandardStream),\n}"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":69,"symbol":"write","kind":"function","lang":"rust","code":"fn write(&mut self, buf: &[u8]) -> io::Result {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref mut w) => w.write(buf),\n BlockBuffered(ref mut w) => w.write(buf),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":79,"symbol":"flush","kind":"function","lang":"rust","code":"fn flush(&mut self) -> io::Result<()> {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref mut w) => w.flush(),\n BlockBuffered(ref mut w) => w.flush(),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":91,"symbol":"supports_color","kind":"function","lang":"rust","code":"fn supports_color(&self) -> bool {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref w) => w.supports_color(),\n BlockBuffered(ref w) => w.supports_color(),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":101,"symbol":"supports_hyperlinks","kind":"function","lang":"rust","code":"fn supports_hyperlinks(&self) -> bool {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref w) => w.supports_hyperlinks(),\n BlockBuffered(ref w) => w.supports_hyperlinks(),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":111,"symbol":"set_color","kind":"function","lang":"rust","code":"fn set_color(&mut self, spec: &termcolor::ColorSpec) -> io::Result<()> {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref mut w) => w.set_color(spec),\n BlockBuffered(ref mut w) => w.set_color(spec),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":121,"symbol":"set_hyperlink","kind":"function","lang":"rust","code":"fn set_hyperlink(&mut self, link: &HyperlinkSpec) -> io::Result<()> {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref mut w) => w.set_hyperlink(link),\n BlockBuffered(ref mut w) => w.set_hyperlink(link),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":131,"symbol":"reset","kind":"function","lang":"rust","code":"fn reset(&mut self) -> io::Result<()> {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref mut w) => w.reset(),\n BlockBuffered(ref mut w) => w.reset(),\n }\n }"} {"repo":"ripgrep","file":"crates/cli/src/wtr.rs","line":141,"symbol":"is_synchronous","kind":"function","lang":"rust","code":"fn is_synchronous(&self) -> bool {\n use self::StandardStreamKind::*;\n\n match self.0 {\n LineBuffered(ref w) => w.is_synchronous(),\n BlockBuffered(ref w) => w.is_synchronous(),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/complete/bash.rs","line":63,"symbol":"generate","kind":"function","lang":"rust","doc":"Generate completions for Bash. Note that these completions are based on what was produced for ripgrep <=13 using Clap 2.x. Improvements on this are welcome.","code":"pub(crate) fn generate() -> String {\n let mut opts = String::new();\n for flag in FLAGS.iter() {\n opts.push_str(\"--\");\n opts.push_str(flag.name_long());\n opts.push(' ');\n if let Some(short) = flag.name_short() {\n opts.push('-');\n opts.push(char::from(short));\n opts.push(' ');\n }\n if let Some(name) = flag.name_negated() {\n opts.push_str(\"--\");\n opts.push_str(name);\n opts.push(' ');\n }\n }\n opts.push_str(\" ...\");\n\n let mut cases = String::new();\n for flag in FLAGS.iter() {\n let template = if !flag.doc_choices().is_empty() {\n let choices = flag.doc_choices().join(\" \");\n TEMPLATE_CASE_CHOICES.trim_end().replace(\"!CHOICES!\", &choices)\n } else {\n TEMPLATE_CASE.trim_end().to_string()\n };\n let name = format!(\"--{}\", flag.name_long());\n cases.push_str(&template.replace(\"!FLAG!\", &name));\n if let Some(short) = flag.name_short() {\n let name = format!(\"-{}\", char::from(short));\n cases.push_str(&template.replace(\"!FLAG!\", &name));\n }\n if let "} {"repo":"ripgrep","file":"crates/core/flags/complete/fish.rs","line":13,"symbol":"generate","kind":"function","lang":"rust","doc":"Generate completions for Fish. Reference: ","code":"pub(crate) fn generate() -> String {\n let mut out = String::new();\n out.push_str(include_str!(\"prelude.fish\"));\n out.push('\\n');\n for flag in FLAGS.iter() {\n let short = match flag.name_short() {\n None => \"\".to_string(),\n Some(byte) => format!(\"-s {}\", char::from(byte)),\n };\n let long = flag.name_long();\n let doc = flag.doc_short().replace(\"'\", \"\\\\'\");\n let mut completion = TEMPLATE\n .replace(\"!SHORT!\", &short)\n .replace(\"!LONG!\", &long)\n .replace(\"!DOC!\", &doc);\n\n match flag.completion_type() {\n CompletionType::Filename => {\n completion.push_str(\" -r -F\");\n }\n CompletionType::Executable => {\n completion.push_str(\" -r -f -a '(__fish_complete_command)'\");\n }\n CompletionType::Filetype => {\n completion.push_str(\n \" -r -f -a '(rg --type-list | string replace : \\\\t)'\",\n );\n }\n CompletionType::Encoding => {\n completion.push_str(\" -r -f -a '\");\n completion.push_str(super::ENCODINGS);\n "} {"repo":"ripgrep","file":"crates/core/flags/complete/powershell.rs","line":43,"symbol":"generate","kind":"function","lang":"rust","doc":"Generate completions for PowerShell. Note that these completions are based on what was produced for ripgrep <=13 using Clap 2.x. Improvements on this are welcome.","code":"pub(crate) fn generate() -> String {\n let mut flags = String::new();\n for (i, flag) in FLAGS.iter().enumerate() {\n let doc = flag.doc_short().replace(\"'\", \"''\");\n\n let dash_name = format!(\"--{}\", flag.name_long());\n let name = flag.name_long();\n if i > 0 {\n flags.push('\\n');\n }\n flags.push_str(\" \");\n flags.push_str(\n &TEMPLATE_FLAG\n .replace(\"!DASH_NAME!\", &dash_name)\n .replace(\"!NAME!\", &name)\n .replace(\"!DOC!\", &doc),\n );\n\n if let Some(byte) = flag.name_short() {\n let dash_name = format!(\"-{}\", char::from(byte));\n let name = char::from(byte).to_string();\n flags.push_str(\"\\n \");\n flags.push_str(\n &TEMPLATE_FLAG\n .replace(\"!DASH_NAME!\", &dash_name)\n .replace(\"!NAME!\", &name)\n .replace(\"!DOC!\", &doc),\n );\n }\n\n if let Some(negated) = flag.name_negated() {\n let dash_name = format!(\"--{negated}\");\n flags.push_str(\"\\n \");\n flags.push_str(\n &TEMPLATE_FLA"} {"repo":"ripgrep","file":"crates/core/flags/complete/prelude.fish","line":2,"symbol":"__rg_contains_opt","kind":"function","lang":"fish","code":"function __rg_contains_opt --description 'Specialized __fish_contains_opt'\n # Cache the config file because this function is called many times per\n # completion attempt.\n # The cache will persist for the entire shell session (even if the\n # variable or the file contents change).\n if not set -q __rg_config\n set -g __rg_config\n if set -qx RIPGREP_CONFIG_PATH\n set __rg_config (\n cat -- $RIPGREP_CONFIG_PATH 2>/dev/null \\\n | string trim \\\n | string match -rv '^$|^#'\n )\n end\n end\n\n set -l commandline (commandline -cpo) (commandline -ct) $__rg_config\n\n if contains -- \"--$argv[1]\" $commandline\n return 0\n end\n\n if set -q argv[2]\n if string match -qr -- \"^-[^-]*$argv[2]\" $commandline\n return 0\n end\n end\n\n return 1\nend"} {"repo":"ripgrep","file":"crates/core/flags/complete/prelude.fish","line":2,"symbol":"--description","kind":"function","lang":"fish","code":"function __rg_contains_opt --description 'Specialized __fish_contains_opt'\n # Cache the config file because this function is called many times per\n # completion attempt.\n # The cache will persist for the entire shell session (even if the\n # variable or the file contents change).\n if not set -q __rg_config\n set -g __rg_config\n if set -qx RIPGREP_CONFIG_PATH\n set __rg_config (\n cat -- $RIPGREP_CONFIG_PATH 2>/dev/null \\\n | string trim \\\n | string match -rv '^$|^#'\n )\n end\n end\n\n set -l commandline (commandline -cpo) (commandline -ct) $__rg_config\n\n if contains -- \"--$argv[1]\" $commandline\n return 0\n end\n\n if set -q argv[2]\n if string match -qr -- \"^-[^-]*$argv[2]\" $commandline\n return 0\n end\n end\n\n return 1\nend"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":15,"symbol":"_rg","kind":"function","lang":"bash","code":"_rg() {\n local no='!'\n local -a args\n\n # ripgrep has many options which negate the effect of a more common one — for\n # example, `--no-column` to negate `--column`, and `--messages` to negate\n # `--no-messages`. There are so many of these, and they're so infrequently\n # used, that some users will probably find it irritating if they're completed\n # indiscriminately, so let's not do that unless either the current prefix\n # matches one of those negation options or the user has the `complete-all`\n # style set. Note that this prefix check has to be updated manually to account\n # for all of the potential negation options listed below!\n if\n # We also want to list all of these options during testing\n [[ $_RG_COMPLETE_LIST_ARGS == (1|t*|y*) ]] ||\n # --[imnpru]* => --ignore*, --messages, --no-*, --pcre2-unicode,\n # --require-git, --unicode\n [[ $PREFIX$SUFFIX == --[imnpru]* ]] ||\n zstyle -t \":completion:${curcontext}:\" complete-all\n then\n no=\n fi\n\n args=(\n + '(exclusive)'\n '(: * -)'{-h,--help}'[display help information]'\n '(: * -)'{-V,--version}'[display version information]'\n '(: * -)'--pcre2-version'[print the version of PCRE2 us"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":16,"symbol":"no","kind":"variable","lang":"bash","code":"no='!'"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":35,"symbol":"no","kind":"variable","lang":"bash","code":"no="} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":38,"symbol":"args","kind":"variable","lang":"bash","code":"args=(\n + '(exclusive)'\n '(: * -)'{-h,--help}'[display help information]'\n '(: * -)'{-V,--version}'[display version information]'\n '(: * -)'--pcre2-version'[print the version of PCRE2 used by ripgrep, if available]'\n\n + '(buffered)'\n '--line-buffered[force line buffering]'\n $no\"--no-line-buffered[don't force line buffering]\"\n '--block-buffered[force block buffering]'\n $no\"--no-block-buffered[don't force block buffering]\"\n\n + '(byte-offset)'\n {-b,--byte-offset}'[show 0-based byte offset for each matching line]'\n $no\"--no-byte-offset[don't show byte offset for each matching line]\"\n\n + '(case)'\n {-i,--ignore-case}'[search case-insensitively]'\n {-s,--case-sensitive}'[search case-sensitively]'\n {-S,--smart-case}'[search case-insensitively if pattern is all lowercase]'\n\n + '(context-a)'\n '(context-c)'{-A+,--after-context=}'[specify lines to show after each match]: :\\\n _numbers -d0 -l0 \"lines of context after match\"\n '\n\n + '(context-b)'\n '(context-c)'{-B+,--before-context=}'[specify lines to show before each match]: :\\\n _numbers -d0 -l0 \"lines of context before match\"\n '\n\n + '(context-c)'\n '(context-a contex"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":373,"symbol":"_rg_color_specs","kind":"function","lang":"bash","code":"_rg_color_specs() {\n local tag=color-specs\n\n if compset -P '[^:]##:(bg|fg):'; then\n _describe -t $tag 'color name or r,g,b' '(\n black blue green red cyan magenta yellow white\n )'\n\n elif compset -P '[^:]##:style:'; then\n _describe -t $tag 'style name' '(\n {,no}bold {,no}intense {,no}underline\n )'\n\n elif compset -P '[^:]##:'; then\n _describe -t $tag 'color/style attribute' \\\n '(\n bg:\"specify background color\"\n fg:\"specify foreground color\"\n style:\"specify text style\"\n )' -r: -S: \\\n -- \\\n '( none:\"clear color/style for type\" )'\n\n else\n _describe -t $tag 'color/style type' '(\n column:\"specify coloring for column numbers\"\n line:\"specify coloring for line numbers\"\n match:\"specify coloring for match text\"\n highlight:\"specify coloring for matching lines\"\n path:\"specify coloring for file names\"\n )' -r: -S:\n fi\n}"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":374,"symbol":"tag","kind":"variable","lang":"bash","code":"tag=color-specs"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":409,"symbol":"_rg_type_specs","kind":"function","lang":"bash","code":"_rg_type_specs() {\n local ret=1\n local -a expl\n\n if compset -P '[^:]##:include:'; then\n _sequence -s , _rg_types && ret=0\n\n elif compset -P '[^:]##:'; then\n _describe -t type-specs-include 'include directive' '(\n include:\"include other type definitions\"\n )' -r: -S: && ret=0\n _wanted type-specs-glob expl 'glob pattern' _files && ret=0\n\n else\n _wanted type-specs-name expl 'file type (or new name)' \\\n _rg_types -r: -S: && ret=0\n fi\n\n return ret\n}"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":410,"symbol":"ret","kind":"variable","lang":"bash","code":"ret=1"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":414,"symbol":"ret","kind":"variable","lang":"bash","code":"ret=0"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":419,"symbol":"ret","kind":"variable","lang":"bash","code":"ret=0"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":420,"symbol":"ret","kind":"variable","lang":"bash","code":"ret=0"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":424,"symbol":"ret","kind":"variable","lang":"bash","code":"ret=0"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":432,"symbol":"_rg_encodings","kind":"function","lang":"bash","code":"_rg_encodings() {\n local -aU encodings=(\n!ENCODINGS!\n )\n encodings=( ${encodings//:/\\\\:} )\n _describe -t encodings encoding encodings \"$@\"\n}"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":433,"symbol":"encodings","kind":"variable","lang":"bash","code":"encodings=(\n!ENCODINGS!\n )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":436,"symbol":"encodings","kind":"variable","lang":"bash","code":"encodings=( ${encodings//:/\\\\:} )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":442,"symbol":"_rg_types","kind":"function","lang":"bash","code":"_rg_types() {\n local -aU types=(\n # this assumes none of the patterns contain colons\n ${(@)${(f)\"$( _call_program types $words[1] --type-list )\"}//:[[:space:]]##/:}\n )\n\n zstyle -t \":completion:${curcontext}:types\" extra-verbose ||\n types=( ${types%%:*} )\n\n _describe -t types 'file type' types \"$@\"\n}"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":443,"symbol":"types","kind":"variable","lang":"bash","code":"types=(\n # this assumes none of the patterns contain colons\n ${(@)"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":449,"symbol":"types","kind":"variable","lang":"bash","code":"types=( ${types%%:*} )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":456,"symbol":"_rg_hyperlink_format_aliases","kind":"function","lang":"bash","code":"_rg_hyperlink_format_aliases() {\n _describe -t format-aliases 'hyperlink format alias' '(\n!HYPERLINK_ALIASES!\n )' \"$@\"\n}"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":468,"symbol":"bs","kind":"variable","lang":"bash","code":"bs=\\\\"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":470,"symbol":"sfx","kind":"variable","lang":"bash","code":"sfx=( -S \"$bs}\" )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":471,"symbol":"rmv","kind":"variable","lang":"bash","code":"rmv=( -r '}\\-' )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":474,"symbol":"sfx","kind":"variable","lang":"bash","code":"sfx=( -S '' )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":477,"symbol":"pfx","kind":"variable","lang":"bash","code":"pfx=( -P \"$bs{\" )"} {"repo":"ripgrep","file":"crates/core/flags/complete/rg.zsh","line":479,"symbol":"WSL_DISTRO_NAME","kind":"variable","lang":"bash","code":"WSL_DISTRO_NAME=${WSL_DISTRO_NAME:-\\$WSL_DISTRO_NAME}"} {"repo":"ripgrep","file":"crates/core/flags/complete/zsh.rs","line":21,"symbol":"generate","kind":"function","lang":"rust","doc":"Generate completions for zsh.","code":"pub(crate) fn generate() -> String {\n let hyperlink_alias_descriptions = grep::printer::hyperlink_aliases()\n .iter()\n .map(|alias| {\n format!(r#\" {}:\"{}\"\"#, alias.name(), alias.description())\n })\n .collect::>()\n .join(\"\\n\");\n include_str!(\"rg.zsh\")\n .replace(\"!ENCODINGS!\", super::ENCODINGS.trim_end())\n .replace(\"!HYPERLINK_ALIASES!\", &hyperlink_alias_descriptions)\n}"} {"repo":"ripgrep","file":"crates/core/flags/config.rs","line":16,"symbol":"args","kind":"function","lang":"rust","doc":"Return a sequence of arguments derived from ripgrep rc configuration files.","code":"pub fn args() -> Vec {\n let config_path = match std::env::var_os(\"RIPGREP_CONFIG_PATH\") {\n None => {\n log::debug!(\n \"RIPGREP_CONFIG_PATH environment variable is not set, \\\n therefore not reading any config file\"\n );\n return vec![];\n }\n Some(config_path) => {\n if config_path.is_empty() {\n return vec![];\n }\n PathBuf::from(config_path)\n }\n };\n let (args, errs) = match parse(&config_path) {\n Ok((args, errs)) => (args, errs),\n Err(err) => {\n message!(\n \"failed to read the file specified in RIPGREP_CONFIG_PATH: {}\",\n err\n );\n return vec![];\n }\n };\n if !errs.is_empty() {\n for err in errs {\n message!(\"{}:{}\", config_path.display(), err);\n }\n }\n log::debug!(\n \"{}: arguments loaded from config file: {:?}\",\n config_path.display(),\n args\n );\n args\n}"} {"repo":"ripgrep","file":"crates/core/flags/config.rs","line":63,"symbol":"parse","kind":"function","lang":"rust","doc":"On success, this returns a set of shell arguments, in order, that should be pre-pended to the arguments given to ripgrep at the command line. If the file could not be read, then an error is returned. If there was a problem parsing one or more lines in the file, then errors are returned for each line in addition to successfully parsed arguments.","code":"fn parse>(\n path: P,\n) -> anyhow::Result<(Vec, Vec)> {\n let path = path.as_ref();\n match std::fs::File::open(&path) {\n Ok(file) => parse_reader(file),\n Err(err) => anyhow::bail!(\"{}: {}\", path.display(), err),\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/config.rs","line":84,"symbol":"parse_reader","kind":"function","lang":"rust","doc":"On success, this returns a set of shell arguments, in order, that should be pre-pended to the arguments given to ripgrep at the command line. If the reader could not be read, then an error is returned. If there was a problem parsing one or more lines, then errors are returned for each line in addition to successfully parsed arguments.","code":"fn parse_reader(\n rdr: R,\n) -> anyhow::Result<(Vec, Vec)> {\n let mut bufrdr = std::io::BufReader::new(rdr);\n let (mut args, mut errs) = (vec![], vec![]);\n let mut line_number = 0;\n bufrdr.for_byte_line_with_terminator(|line| {\n line_number += 1;\n\n let line = line.trim();\n if line.is_empty() || line[0] == b'#' {\n return Ok(true);\n }\n match line.to_os_str() {\n Ok(osstr) => {\n args.push(osstr.to_os_string());\n }\n Err(err) => {\n errs.push(anyhow::anyhow!(\"{line_number}: {err}\"));\n }\n }\n Ok(true)\n })?;\n Ok((args, errs))\n}"} {"repo":"ripgrep","file":"crates/core/flags/config.rs","line":116,"symbol":"basic","kind":"function","lang":"rust","code":"fn basic() {\n let (args, errs) = parse_reader(\n &b\"\\\n# Test\n--context=0\n --smart-case\n-u\n\n\n # --bar\n--foo\n\"[..],\n )\n .unwrap();\n assert!(errs.is_empty());\n let args: Vec =\n args.into_iter().map(|s| s.into_string().unwrap()).collect();\n assert_eq!(args, vec![\"--context=0\", \"--smart-case\", \"-u\", \"--foo\",]);\n }"} {"repo":"ripgrep","file":"crates/core/flags/config.rs","line":139,"symbol":"error","kind":"function","lang":"rust","doc":"We test that we can handle invalid UTF-8 on Unix-like systems.","code":"fn error() {\n use std::os::unix::ffi::OsStringExt;\n\n let (args, errs) = parse_reader(\n &b\"\\\nquux\nfoo\\xFFbar\nbaz\n\"[..],\n )\n .unwrap();\n assert!(errs.is_empty());\n assert_eq!(\n args,\n vec![\n OsString::from(\"quux\"),\n OsString::from_vec(b\"foo\\xFFbar\".to_vec()),\n OsString::from(\"baz\"),\n ]\n );\n }"} {"repo":"ripgrep","file":"crates/core/flags/config.rs","line":164,"symbol":"error","kind":"function","lang":"rust","doc":"... but test that invalid UTF-8 fails on Windows.","code":"fn error() {\n let (args, errs) = parse_reader(\n &b\"\\\nquux\nfoo\\xFFbar\nbaz\n\"[..],\n )\n .unwrap();\n assert_eq!(errs.len(), 1);\n assert_eq!(args, vec![OsString::from(\"quux\"), OsString::from(\"baz\"),]);\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":167,"symbol":"indexing_unsupported_flag","kind":"function","lang":"rust","doc":"If there aren't any flags enabled that don't support indexing, then `None` is returned. The idea of this routine is to start out very paranoid about what is allowed to be used when indexing is enabled. Ideally, most or all of these would eventually become supported.","code":"pub(super) fn indexing_unsupported_flag(\n &self,\n ) -> Option<&'static dyn Flag> {\n if matches!(self.mode, Mode::Search(SearchMode::FilesWithoutMatch)) {\n return Some(&FilesWithoutMatch);\n }\n if matches!(self.binary, BinaryMode::AsText) {\n return Some(&Binary);\n }\n if !matches!(self.encoding, EncodingMode::Auto) {\n return Some(&Encoding);\n }\n if matches!(self.engine, EngineChoice::PCRE2) {\n return Some(&Engine);\n }\n if self.follow {\n return Some(&Follow);\n }\n if !self.globs.is_empty() {\n return Some(&Glob);\n }\n if self.hidden {\n return Some(&Hidden);\n }\n if !self.iglobs.is_empty() {\n return Some(&Glob);\n }\n if !self.ignore_file.is_empty() {\n return Some(&IgnoreFile);\n }\n if self.no_ignore_dot {\n return Some(&NoIgnoreDot);\n }\n if self.no_ignore_exclude {\n return Some(&NoIgnoreExclude);\n }\n if self.no_ignore_files {\n return Some(&NoIgnoreFiles);\n }\n if self.no_ignore_globa"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":233,"symbol":"AfterContext","kind":"type","lang":"rust","doc":"-A/--after-context","code":"struct AfterContext;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":236,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n false\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":239,"symbol":"name_short","kind":"function","lang":"rust","code":"fn name_short(&self) -> Option {\n Some(b'A')\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":242,"symbol":"name_long","kind":"function","lang":"rust","code":"fn name_long(&self) -> &'static str {\n \"after-context\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":245,"symbol":"doc_variable","kind":"function","lang":"rust","code":"fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":248,"symbol":"doc_category","kind":"function","lang":"rust","code":"fn doc_category(&self) -> Category {\n Category::Output\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":251,"symbol":"doc_short","kind":"function","lang":"rust","code":"fn doc_short(&self) -> &'static str {\n \"Show NUM lines after each match.\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":254,"symbol":"doc_long","kind":"function","lang":"rust","code":"fn doc_long(&self) -> &'static str {\n r\"\nShow \\fINUM\\fP lines after each match.\n.sp\nThis overrides the \\flag{passthru} flag and partially overrides the\n\\flag{context} flag.\n\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":263,"symbol":"update","kind":"function","lang":"rust","code":"fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.context.set_after(convert::usize(&v.unwrap_value())?);\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":271,"symbol":"test_after_context","kind":"function","lang":"rust","code":"fn test_after_context() {\n let mkctx = |lines| {\n let mut mode = ContextMode::default();\n mode.set_after(lines);\n mode\n };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ContextMode::default(), args.context);\n\n let args = parse_low_raw([\"--after-context\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"--after-context=5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-A\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-A5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-A5\", \"-A10\"]).unwrap();\n assert_eq!(mkctx(10), args.context);\n\n let args = parse_low_raw([\"-A5\", \"-A0\"]).unwrap();\n assert_eq!(mkctx(0), args.context);\n\n let args = parse_low_raw([\"-A5\", \"--passthru\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n\n let args = parse_low_raw([\"--passthru\", \"-A5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let n = usize::MAX.to_string();\n let args = parse_low_raw([\"--after-context\", n.as_str()]).unwrap();\n assert_eq!(mkctx(usize::M"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":319,"symbol":"AutoHybridRegex","kind":"type","lang":"rust","doc":"--auto-hybrid-regex","code":"struct AutoHybridRegex;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":322,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n true\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":325,"symbol":"name_long","kind":"function","lang":"rust","code":"fn name_long(&self) -> &'static str {\n \"auto-hybrid-regex\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":328,"symbol":"name_negated","kind":"function","lang":"rust","code":"fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-auto-hybrid-regex\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":331,"symbol":"doc_category","kind":"function","lang":"rust","code":"fn doc_category(&self) -> Category {\n Category::Search\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":334,"symbol":"doc_short","kind":"function","lang":"rust","code":"fn doc_short(&self) -> &'static str {\n \"(DEPRECATED) Use PCRE2 if appropriate.\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":337,"symbol":"doc_long","kind":"function","lang":"rust","code":"fn doc_long(&self) -> &'static str {\n r\"\nDEPRECATED. Use \\flag{engine} instead.\n.sp\nWhen this flag is used, ripgrep will dynamically choose between supported regex\nengines depending on the features used in a pattern. When ripgrep chooses a\nregex engine, it applies that choice for every regex provided to ripgrep (e.g.,\nvia multiple \\flag{regexp} or \\flag{file} flags).\n.sp\nAs an example of how this flag might behave, ripgrep will attempt to use\nits default finite automata based regex engine whenever the pattern can be\nsuccessfully compiled with that regex engine. If PCRE2 is enabled and if the\npattern given could not be compiled with the default regex engine, then PCRE2\nwill be automatically used for searching. If PCRE2 isn't available, then this\nflag has no effect because there is only one regex engine to choose from.\n.sp\nIn the future, ripgrep may adjust its heuristics for how it decides which\nregex engine to use. In general, the heuristics will be limited to a static\nanalysis of the patterns, and not to any specific runtime behavior observed\nwhile searching files.\n.sp\nThe primary downside of using this flag is that it may not always be obvious\nwhich regex engine ripgrep use"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":367,"symbol":"update","kind":"function","lang":"rust","code":"fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n let mode = if v.unwrap_switch() {\n EngineChoice::Auto\n } else {\n EngineChoice::Default\n };\n args.engine = mode;\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":380,"symbol":"test_auto_hybrid_regex","kind":"function","lang":"rust","code":"fn test_auto_hybrid_regex() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args = parse_low_raw([\"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--no-auto-hybrid-regex\"])\n .unwrap();\n assert_eq!(EngineChoice::Default, args.engine);\n\n let args =\n parse_low_raw([\"--no-auto-hybrid-regex\", \"--auto-hybrid-regex\"])\n .unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args = parse_low_raw([\"--auto-hybrid-regex\", \"-P\"]).unwrap();\n assert_eq!(EngineChoice::PCRE2, args.engine);\n\n let args = parse_low_raw([\"-P\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--engine=auto\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--engine=default\", \"--auto-hybrid-regex\"]).unwrap();\n assert_eq!(EngineChoice::Auto, args.engine);\n\n let args =\n parse_low_raw([\"--auto-hybrid-regex\", \"--engine=default\"]).unwrap();\n assert_"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":418,"symbol":"BeforeContext","kind":"type","lang":"rust","doc":"-B/--before-context","code":"struct BeforeContext;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":421,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n false\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":424,"symbol":"name_short","kind":"function","lang":"rust","code":"fn name_short(&self) -> Option {\n Some(b'B')\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":427,"symbol":"name_long","kind":"function","lang":"rust","code":"fn name_long(&self) -> &'static str {\n \"before-context\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":430,"symbol":"doc_variable","kind":"function","lang":"rust","code":"fn doc_variable(&self) -> Option<&'static str> {\n Some(\"NUM\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":433,"symbol":"doc_category","kind":"function","lang":"rust","code":"fn doc_category(&self) -> Category {\n Category::Output\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":436,"symbol":"doc_short","kind":"function","lang":"rust","code":"fn doc_short(&self) -> &'static str {\n \"Show NUM lines before each match.\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":439,"symbol":"doc_long","kind":"function","lang":"rust","code":"fn doc_long(&self) -> &'static str {\n r\"\nShow \\fINUM\\fP lines before each match.\n.sp\nThis overrides the \\flag{passthru} flag and partially overrides the\n\\flag{context} flag.\n\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":448,"symbol":"update","kind":"function","lang":"rust","code":"fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.context.set_before(convert::usize(&v.unwrap_value())?);\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":456,"symbol":"test_before_context","kind":"function","lang":"rust","code":"fn test_before_context() {\n let mkctx = |lines| {\n let mut mode = ContextMode::default();\n mode.set_before(lines);\n mode\n };\n\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(ContextMode::default(), args.context);\n\n let args = parse_low_raw([\"--before-context\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"--before-context=5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-B\", \"5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-B5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let args = parse_low_raw([\"-B5\", \"-B10\"]).unwrap();\n assert_eq!(mkctx(10), args.context);\n\n let args = parse_low_raw([\"-B5\", \"-B0\"]).unwrap();\n assert_eq!(mkctx(0), args.context);\n\n let args = parse_low_raw([\"-B5\", \"--passthru\"]).unwrap();\n assert_eq!(ContextMode::Passthru, args.context);\n\n let args = parse_low_raw([\"--passthru\", \"-B5\"]).unwrap();\n assert_eq!(mkctx(5), args.context);\n\n let n = usize::MAX.to_string();\n let args = parse_low_raw([\"--before-context\", n.as_str()]).unwrap();\n assert_eq!(mkctx(usi"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":504,"symbol":"Binary","kind":"type","lang":"rust","doc":"--binary","code":"struct Binary;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":507,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n true\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":510,"symbol":"name_long","kind":"function","lang":"rust","code":"fn name_long(&self) -> &'static str {\n \"binary\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":513,"symbol":"name_negated","kind":"function","lang":"rust","code":"fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-binary\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":516,"symbol":"doc_category","kind":"function","lang":"rust","code":"fn doc_category(&self) -> Category {\n Category::Filter\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":519,"symbol":"doc_short","kind":"function","lang":"rust","code":"fn doc_short(&self) -> &'static str {\n \"Search binary files.\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":522,"symbol":"doc_long","kind":"function","lang":"rust","code":"fn doc_long(&self) -> &'static str {\n r\"\nEnabling this flag will cause ripgrep to search binary files. By default,\nripgrep attempts to automatically skip binary files in order to improve the\nrelevance of results and make the search faster.\n.sp\nBinary files are heuristically detected based on whether they contain a\n\\fBNUL\\fP byte or not. By default (without this flag set), once a \\fBNUL\\fP\nbyte is seen, ripgrep will stop searching the file. Usually, \\fBNUL\\fP bytes\noccur in the beginning of most binary files. If a \\fBNUL\\fP byte occurs after\na match, then ripgrep will not print the match, stop searching that file, and\nemit a warning that some matches are being suppressed.\n.sp\nIn contrast, when this flag is provided, ripgrep will continue searching a\nfile even if a \\fBNUL\\fP byte is found. In particular, if a \\fBNUL\\fP byte is\nfound then ripgrep will continue searching until either a match is found or\nthe end of the file is reached, whichever comes sooner. If a match is found,\nthen ripgrep will stop and print a warning saying that the search stopped\nprematurely.\n.sp\nIf you want ripgrep to search a file without any special \\fBNUL\\fP byte\nhandling at all (and potentially print b"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":558,"symbol":"update","kind":"function","lang":"rust","code":"fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.binary = if v.unwrap_switch() {\n BinaryMode::SearchAndSuppress\n } else {\n BinaryMode::Auto\n };\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":570,"symbol":"test_binary","kind":"function","lang":"rust","code":"fn test_binary() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"--binary\", \"--no-binary\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n\n let args = parse_low_raw([\"--no-binary\", \"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"--binary\", \"-a\"]).unwrap();\n assert_eq!(BinaryMode::AsText, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--binary\"]).unwrap();\n assert_eq!(BinaryMode::SearchAndSuppress, args.binary);\n\n let args = parse_low_raw([\"-a\", \"--no-binary\"]).unwrap();\n assert_eq!(BinaryMode::Auto, args.binary);\n}"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":595,"symbol":"BlockBuffered","kind":"type","lang":"rust","doc":"--block-buffered","code":"struct BlockBuffered;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":598,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n true\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":601,"symbol":"name_long","kind":"function","lang":"rust","code":"fn name_long(&self) -> &'static str {\n \"block-buffered\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":604,"symbol":"name_negated","kind":"function","lang":"rust","code":"fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-block-buffered\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":607,"symbol":"doc_category","kind":"function","lang":"rust","code":"fn doc_category(&self) -> Category {\n Category::Output\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":610,"symbol":"doc_short","kind":"function","lang":"rust","code":"fn doc_short(&self) -> &'static str {\n \"Force block buffering.\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":613,"symbol":"doc_long","kind":"function","lang":"rust","code":"fn doc_long(&self) -> &'static str {\n r\"\nWhen enabled, ripgrep will use block buffering. That is, whenever a matching\nline is found, it will be written to an in-memory buffer and will not be\nwritten to stdout until the buffer reaches a certain size. This is the default\nwhen ripgrep's stdout is redirected to a pipeline or a file. When ripgrep's\nstdout is connected to a tty, line buffering will be used by default. Forcing\nblock buffering can be useful when dumping a large amount of contents to a tty.\n.sp\nThis overrides the \\flag{line-buffered} flag.\n\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":626,"symbol":"update","kind":"function","lang":"rust","code":"fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.buffer = if v.unwrap_switch() {\n BufferMode::Block\n } else {\n BufferMode::Auto\n };\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":638,"symbol":"test_block_buffered","kind":"function","lang":"rust","code":"fn test_block_buffered() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(BufferMode::Auto, args.buffer);\n\n let args = parse_low_raw([\"--block-buffered\"]).unwrap();\n assert_eq!(BufferMode::Block, args.buffer);\n\n let args =\n parse_low_raw([\"--block-buffered\", \"--no-block-buffered\"]).unwrap();\n assert_eq!(BufferMode::Auto, args.buffer);\n\n let args = parse_low_raw([\"--block-buffered\", \"--line-buffered\"]).unwrap();\n assert_eq!(BufferMode::Line, args.buffer);\n}"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":655,"symbol":"ByteOffset","kind":"type","lang":"rust","doc":"--byte-offset","code":"struct ByteOffset;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":658,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n true\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":661,"symbol":"name_short","kind":"function","lang":"rust","code":"fn name_short(&self) -> Option {\n Some(b'b')\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":664,"symbol":"name_long","kind":"function","lang":"rust","code":"fn name_long(&self) -> &'static str {\n \"byte-offset\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":667,"symbol":"name_negated","kind":"function","lang":"rust","code":"fn name_negated(&self) -> Option<&'static str> {\n Some(\"no-byte-offset\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":670,"symbol":"doc_category","kind":"function","lang":"rust","code":"fn doc_category(&self) -> Category {\n Category::Output\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":673,"symbol":"doc_short","kind":"function","lang":"rust","code":"fn doc_short(&self) -> &'static str {\n \"Print the byte offset for each matching line.\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":676,"symbol":"doc_long","kind":"function","lang":"rust","code":"fn doc_long(&self) -> &'static str {\n r\"\nPrint the 0-based byte offset within the input file before each line of output.\nIf \\flag{only-matching} is specified, print the offset of the matched text\nitself.\n.sp\nIf ripgrep does transcoding, then the byte offset is in terms of the result\nof transcoding and not the original data. This applies similarly to other\ntransformations on the data, such as decompression or a \\flag{pre} filter.\n\"\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":688,"symbol":"update","kind":"function","lang":"rust","code":"fn update(&self, v: FlagValue, args: &mut LowArgs) -> anyhow::Result<()> {\n args.byte_offset = v.unwrap_switch();\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":696,"symbol":"test_byte_offset","kind":"function","lang":"rust","code":"fn test_byte_offset() {\n let args = parse_low_raw(None::<&str>).unwrap();\n assert_eq!(false, args.byte_offset);\n\n let args = parse_low_raw([\"--byte-offset\"]).unwrap();\n assert_eq!(true, args.byte_offset);\n\n let args = parse_low_raw([\"-b\"]).unwrap();\n assert_eq!(true, args.byte_offset);\n\n let args = parse_low_raw([\"--byte-offset\", \"--no-byte-offset\"]).unwrap();\n assert_eq!(false, args.byte_offset);\n\n let args = parse_low_raw([\"--no-byte-offset\", \"-b\"]).unwrap();\n assert_eq!(true, args.byte_offset);\n}"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":715,"symbol":"CaseSensitive","kind":"type","lang":"rust","doc":"-s/--case-sensitive","code":"struct CaseSensitive;"} {"repo":"ripgrep","file":"crates/core/flags/defs.rs","line":718,"symbol":"is_switch","kind":"function","lang":"rust","code":"fn is_switch(&self) -> bool {\n true\n }"} {"repo":"ripgrep","file":"crates/core/flags/doc/help.rs","line":24,"symbol":"generate_short","kind":"function","lang":"rust","doc":"Generate short documentation, i.e., for `-h`.","code":"pub(crate) fn generate_short() -> String {\n let mut cats: BTreeMap, Vec)> =\n BTreeMap::new();\n let (mut maxcol1, mut maxcol2) = (0, 0);\n for flag in FLAGS.iter().copied() {\n let columns =\n cats.entry(flag.doc_category()).or_insert((vec![], vec![]));\n let (col1, col2) = generate_short_flag(flag);\n maxcol1 = maxcol1.max(col1.len());\n maxcol2 = maxcol2.max(col2.len());\n columns.0.push(col1);\n columns.1.push(col2);\n }\n let mut out =\n TEMPLATE_SHORT.replace(\"!!VERSION!!\", &version::generate_digits());\n for (cat, (col1, col2)) in cats.iter() {\n let var = format!(\"!!{name}!!\", name = cat.as_str());\n if !cfg!(feature = \"unstable-index\")\n && matches!(cat, crate::flags::Category::Indexing)\n {\n out = out.replace(\n &var,\n &format!(\" {}\", crate::flags::INDEXING_NOT_SUPPORTED),\n );\n } else {\n let val = format_short_columns(col1, col2, maxcol1, maxcol2);\n out = out.replace(&var, &val);\n }\n }\n out\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/help.rs","line":60,"symbol":"generate_short_flag","kind":"function","lang":"rust","doc":"Generate short for a single flag. The first element corresponds to the flag name while the second element corresponds to the documentation string.","code":"fn generate_short_flag(flag: &dyn Flag) -> (String, String) {\n let (mut col1, mut col2) = (String::new(), String::new());\n\n // Some of the variable names are fine for longer form\n // docs, but they make the succinct short help very noisy.\n // So just shorten some of them.\n let var = flag.doc_variable().map(|s| {\n let mut s = s.to_string();\n s = s.replace(\"SEPARATOR\", \"SEP\");\n s = s.replace(\"REPLACEMENT\", \"TEXT\");\n s = s.replace(\"NUM+SUFFIX?\", \"NUM\");\n s\n });\n\n // Generate the first column, the flag name.\n if let Some(byte) = flag.name_short() {\n let name = char::from(byte);\n write!(col1, r\"-{name}\");\n write!(col1, r\", \");\n }\n write!(col1, r\"--{name}\", name = flag.name_long());\n if let Some(var) = var.as_ref() {\n write!(col1, r\"={var}\");\n }\n\n // And now the second column, with the description.\n write!(col2, \"{}\", flag.doc_short());\n\n (col1, col2)\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/help.rs","line":96,"symbol":"format_short_columns","kind":"function","lang":"rust","doc":"Write two columns of documentation. `maxcol1` should be the maximum length (in bytes) of the first column, while `maxcol2` should be the maximum length (in bytes) of the second column.","code":"fn format_short_columns(\n col1: &[String],\n col2: &[String],\n maxcol1: usize,\n _maxcol2: usize,\n) -> String {\n assert_eq!(col1.len(), col2.len(), \"columns must have equal length\");\n const PAD: usize = 2;\n let mut out = String::new();\n for (i, (c1, c2)) in col1.iter().zip(col2.iter()).enumerate() {\n if i > 0 {\n write!(out, \"\\n\");\n }\n\n let pad = maxcol1 - c1.len() + PAD;\n write!(out, \" \");\n write!(out, \"{c1}\");\n write!(out, \"{}\", \" \".repeat(pad));\n write!(out, \"{c2}\");\n }\n out\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/help.rs","line":120,"symbol":"generate_long","kind":"function","lang":"rust","doc":"Generate long documentation, i.e., for `--help`.","code":"pub(crate) fn generate_long() -> String {\n let mut cats = BTreeMap::new();\n for flag in FLAGS.iter().copied() {\n let mut cat = cats.entry(flag.doc_category()).or_insert(String::new());\n if !cat.is_empty() {\n write!(cat, \"\\n\\n\");\n }\n generate_long_flag(flag, &mut cat);\n }\n\n let mut out =\n TEMPLATE_LONG.replace(\"!!VERSION!!\", &version::generate_digits());\n for (cat, value) in cats.iter() {\n let var = format!(\"!!{name}!!\", name = cat.as_str());\n if !cfg!(feature = \"unstable-index\")\n && matches!(cat, crate::flags::Category::Indexing)\n {\n out = out.replace(\n &var,\n &format!(\" {}\", crate::flags::INDEXING_NOT_SUPPORTED),\n );\n } else {\n out = out.replace(&var, value);\n }\n }\n out\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/help.rs","line":149,"symbol":"generate_long_flag","kind":"function","lang":"rust","doc":"Write generated documentation for `flag` to `out`.","code":"fn generate_long_flag(flag: &dyn Flag, out: &mut String) {\n if let Some(byte) = flag.name_short() {\n let name = char::from(byte);\n write!(out, r\" -{name}\");\n if let Some(var) = flag.doc_variable() {\n write!(out, r\" {var}\");\n }\n write!(out, r\", \");\n } else {\n write!(out, r\" \");\n }\n\n let name = flag.name_long();\n write!(out, r\"--{name}\");\n if let Some(var) = flag.doc_variable() {\n write!(out, r\"={var}\");\n }\n write!(out, \"\\n\");\n\n let doc = flag.doc_long().trim();\n let doc = super::render_custom_markup(doc, \"flag\", |name, out| {\n let Some(flag) = crate::flags::parse::lookup(name) else {\n unreachable!(r\"found unrecognized \\flag{{{name}}} in --help docs\")\n };\n if let Some(name) = flag.name_short() {\n write!(out, r\"-{}/\", char::from(name));\n }\n write!(out, r\"--{}\", flag.name_long());\n });\n let doc = super::render_custom_markup(&doc, \"flag-negate\", |name, out| {\n let Some(flag) = crate::flags::parse::lookup(name) else {\n unreachable!(\n r\"found unrecognized \\flag-negate{{{name}}} in --help docs\"\n "} {"repo":"ripgrep","file":"crates/core/flags/doc/help.rs","line":234,"symbol":"remove_roff","kind":"function","lang":"rust","doc":"Removes roff syntax from `v` such that the result is approximately plain text readable. This is basically a mish mash of heuristics based on the specific roff used in the docs for the flags in this tool. If new kinds of roff are used in the docs, then this may need to be updated to handle them.","code":"fn remove_roff(v: &str) -> String {\n let mut lines = vec![];\n for line in v.trim().lines() {\n assert!(!line.is_empty(), \"roff should have no empty lines\");\n if line.starts_with(\".\") {\n if line.starts_with(\".IP \") {\n let item_label = line\n .split(\" \")\n .nth(1)\n .expect(\"first argument to .IP\")\n .replace(r\"\\(bu\", r\"•\")\n .replace(r\"\\fB\", \"\")\n .replace(r\"\\fP\", \":\");\n lines.push(format!(\"{item_label}\"));\n } else if line.starts_with(\".IB \") || line.starts_with(\".BI \") {\n let pieces = line\n .split_whitespace()\n .skip(1)\n .collect::>()\n .concat();\n lines.push(format!(\"{pieces}\"));\n } else if line.starts_with(\".sp\")\n || line.starts_with(\".PP\")\n || line.starts_with(\".TP\")\n {\n lines.push(\"\".to_string());\n }\n } else if line.starts_with(r\"\\fB\") && line.ends_with(r\"\\fP\") {\n let line = line.replace(r\"\\fB\", \"\""} {"repo":"ripgrep","file":"crates/core/flags/doc/man.rs","line":27,"symbol":"generate","kind":"function","lang":"rust","doc":"Returns a `roff` formatted string corresponding to ripgrep's entire man page.","code":"pub(crate) fn generate() -> String {\n let mut cats = BTreeMap::new();\n for flag in FLAGS.iter().copied() {\n let mut cat = cats.entry(flag.doc_category()).or_insert(String::new());\n if !cat.is_empty() {\n writeln!(cat, \".sp\");\n }\n generate_flag(flag, &mut cat);\n }\n\n let mut out = TEMPLATE.replace(\"!!VERSION!!\", &version::generate_digits());\n for (cat, value) in cats.iter() {\n let var = format!(\"!!{name}!!\", name = cat.as_str());\n if !cfg!(feature = \"unstable-index\")\n && matches!(cat, crate::flags::Category::Indexing)\n {\n out = out.replace(&var, crate::flags::INDEXING_NOT_SUPPORTED);\n } else {\n out = out.replace(&var, value);\n }\n }\n out\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/man.rs","line":52,"symbol":"generate_flag","kind":"function","lang":"rust","doc":"Writes `roff` formatted documentation for `flag` to `out`.","code":"fn generate_flag(flag: &'static dyn Flag, out: &mut String) {\n if let Some(byte) = flag.name_short() {\n let name = char::from(byte);\n write!(out, r\"\\fB\\-{name}\\fP\");\n if let Some(var) = flag.doc_variable() {\n write!(out, r\" \\fI{var}\\fP\");\n }\n write!(out, r\", \");\n }\n\n let name = flag.name_long().replace(\"-\", r\"\\-\");\n write!(out, r\"\\fB\\-\\-{name}\\fP\");\n if let Some(var) = flag.doc_variable() {\n write!(out, r\"=\\fI{var}\\fP\");\n }\n write!(out, \"\\n\");\n\n writeln!(out, \".RS 4\");\n let doc = flag.doc_long().trim();\n // Convert \\flag{foo} into something nicer.\n let doc = super::render_custom_markup(doc, \"flag\", |name, out| {\n let Some(flag) = crate::flags::parse::lookup(name) else {\n unreachable!(r\"found unrecognized \\flag{{{name}}} in roff docs\")\n };\n out.push_str(r\"\\fB\");\n if let Some(name) = flag.name_short() {\n write!(out, r\"\\-{}/\", char::from(name));\n }\n write!(out, r\"\\-\\-{}\", flag.name_long().replace(\"-\", r\"\\-\"));\n out.push_str(r\"\\fP\");\n });\n // Convert \\flag-negate{foo} into something nicer.\n let doc = super::render_custom_m"} {"repo":"ripgrep","file":"crates/core/flags/doc/mod.rs","line":18,"symbol":"render_custom_markup","kind":"function","lang":"rust","doc":"The first argument given to `replacement` is the tag value, `...`. The second argument is the buffer that accumulates the full replacement text. Since this function is only intended to be used on doc strings written into the program source code, callers should panic in `replacement` if there are any errors or unexpected circumstances.","code":"fn render_custom_markup(\n mut doc: &str,\n tag: &str,\n mut replacement: impl FnMut(&str, &mut String),\n) -> String {\n let mut out = String::with_capacity(doc.len());\n let tag_prefix = format!(r\"\\{tag}{{\");\n while let Some(offset) = doc.find(&tag_prefix) {\n out.push_str(&doc[..offset]);\n\n let start = offset + tag_prefix.len();\n let Some(end) = doc[start..].find('}').map(|i| start + i) else {\n unreachable!(r\"found {tag_prefix} without closing }}\");\n };\n let name = &doc[start..end];\n replacement(name, &mut out);\n doc = &doc[end + 1..];\n }\n out.push_str(doc);\n out\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":13,"symbol":"generate_digits","kind":"function","lang":"rust","doc":"Generates just the numerical part of the version of ripgrep. This includes the git revision hash.","code":"pub(crate) fn generate_digits() -> String {\n let semver = option_env!(\"CARGO_PKG_VERSION\").unwrap_or(\"N/A\");\n match option_env!(\"RIPGREP_BUILD_GIT_HASH\") {\n None => semver.to_string(),\n Some(hash) => format!(\"{semver} (rev {hash})\"),\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":22,"symbol":"generate_short","kind":"function","lang":"rust","doc":"Generates a short version string of the form `ripgrep x.y.z`.","code":"pub(crate) fn generate_short() -> String {\n let digits = generate_digits();\n format!(\"ripgrep {digits}\")\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":31,"symbol":"generate_long","kind":"function","lang":"rust","doc":"Generates a longer multi-line version string. This includes not only the version of ripgrep but some other information about its build. For example, SIMD support and PCRE2 support.","code":"pub(crate) fn generate_long() -> String {\n let (compile, runtime) = (compile_cpu_features(), runtime_cpu_features());\n\n let mut out = String::new();\n writeln!(out, \"{}\", generate_short()).unwrap();\n writeln!(out).unwrap();\n writeln!(out, \"features:{}\", features().join(\",\")).unwrap();\n if !compile.is_empty() {\n writeln!(out, \"simd(compile):{}\", compile.join(\",\")).unwrap();\n }\n if !runtime.is_empty() {\n writeln!(out, \"simd(runtime):{}\", runtime.join(\",\")).unwrap();\n }\n let (pcre2_version, _) = generate_pcre2();\n writeln!(out, \"\\n{pcre2_version}\").unwrap();\n out\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":53,"symbol":"generate_pcre2","kind":"function","lang":"rust","doc":"Generates multi-line version string with PCRE2 information. This also returns whether PCRE2 is actually available in this build of ripgrep.","code":"pub(crate) fn generate_pcre2() -> (String, bool) {\n let mut out = String::new();\n\n #[cfg(feature = \"pcre2\")]\n {\n use grep::pcre2;\n\n let (major, minor) = pcre2::version();\n write!(out, \"PCRE2 {}.{} is available\", major, minor).unwrap();\n if cfg!(target_pointer_width = \"64\") && pcre2::is_jit_available() {\n writeln!(out, \" (JIT is available)\").unwrap();\n } else {\n writeln!(out, \" (JIT is unavailable)\").unwrap();\n }\n (out, true)\n }\n\n #[cfg(not(feature = \"pcre2\"))]\n {\n writeln!(out, \"PCRE2 is not available in this build of ripgrep.\")\n .unwrap();\n (out, false)\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":83,"symbol":"runtime_cpu_features","kind":"function","lang":"rust","doc":"Returns the relevant SIMD features supported by the CPU at runtime. This is kind of a dirty violation of abstraction, since it assumes knowledge about what specific SIMD features are being used by various components.","code":"fn runtime_cpu_features() -> Vec {\n #[cfg(target_arch = \"x86_64\")]\n {\n let mut features = vec![];\n\n let sse2 = is_x86_feature_detected!(\"sse2\");\n features.push(format!(\"{sign}SSE2\", sign = sign(sse2)));\n\n let ssse3 = is_x86_feature_detected!(\"ssse3\");\n features.push(format!(\"{sign}SSSE3\", sign = sign(ssse3)));\n\n let avx2 = is_x86_feature_detected!(\"avx2\");\n features.push(format!(\"{sign}AVX2\", sign = sign(avx2)));\n\n features\n }\n #[cfg(target_arch = \"aarch64\")]\n {\n let mut features = vec![];\n\n // memchr and aho-corasick only use NEON when it is available at\n // compile time. This isn't strictly necessary, but NEON is supposed\n // to be available for all aarch64 targets. If this isn't true, please\n // file an issue at https://github.com/BurntSushi/memchr.\n let neon = cfg!(target_feature = \"neon\");\n features.push(format!(\"{sign}NEON\", sign = sign(neon)));\n\n features\n }\n #[cfg(not(any(target_arch = \"x86_64\", target_arch = \"aarch64\")))]\n {\n vec![]\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":129,"symbol":"compile_cpu_features","kind":"function","lang":"rust","doc":"knowledge about what specific SIMD features are being used by various components. An easy way to enable everything available on your current CPU is to compile ripgrep with `RUSTFLAGS=\"-C target-cpu=native\"`. But note that the binary produced by this will not be portable.","code":"fn compile_cpu_features() -> Vec {\n #[cfg(target_arch = \"x86_64\")]\n {\n let mut features = vec![];\n\n let sse2 = cfg!(target_feature = \"sse2\");\n features.push(format!(\"{sign}SSE2\", sign = sign(sse2)));\n\n let ssse3 = cfg!(target_feature = \"ssse3\");\n features.push(format!(\"{sign}SSSE3\", sign = sign(ssse3)));\n\n let avx2 = cfg!(target_feature = \"avx2\");\n features.push(format!(\"{sign}AVX2\", sign = sign(avx2)));\n\n features\n }\n #[cfg(target_arch = \"aarch64\")]\n {\n let mut features = vec![];\n\n let neon = cfg!(target_feature = \"neon\");\n features.push(format!(\"{sign}NEON\", sign = sign(neon)));\n\n features\n }\n #[cfg(not(any(target_arch = \"x86_64\", target_arch = \"aarch64\")))]\n {\n vec![]\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":161,"symbol":"features","kind":"function","lang":"rust","doc":"Returns a list of \"features\" supported (or not) by this build of ripgrpe.","code":"fn features() -> Vec {\n let mut features = vec![];\n\n let pcre2 = cfg!(feature = \"pcre2\");\n features.push(format!(\"{sign}pcre2\", sign = sign(pcre2)));\n\n features\n}"} {"repo":"ripgrep","file":"crates/core/flags/doc/version.rs","line":171,"symbol":"sign","kind":"function","lang":"rust","doc":"Returns `+` when `enabled` is `true` and `-` otherwise.","code":"fn sign(enabled: bool) -> &'static str {\n if enabled { \"+\" } else { \"-\" }\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":36,"symbol":"HiArgs","kind":"type","lang":"rust","doc":"and wishy washy. The main idea here is that high level arguments generally require all of CLI parsing to be finished. For example, one cannot construct a glob matcher until all of the glob patterns are known. So while low level arguments are collected during parsing itself, high level arguments aren't created until parsing has completely finished.","code":"pub(crate) struct HiArgs {\n binary: BinaryDetection,\n boundary: Option,\n buffer: BufferMode,\n byte_offset: bool,\n case: CaseMode,\n color: ColorChoice,\n colors: grep::printer::ColorSpecs,\n column: bool,\n context: ContextMode,\n context_separator: ContextSeparator,\n crlf: bool,\n cwd: PathBuf,\n dfa_size_limit: Option,\n encoding: EncodingMode,\n engine: EngineChoice,\n field_context_separator: FieldContextSeparator,\n field_match_separator: FieldMatchSeparator,\n file_separator: Option>,\n fixed_strings: bool,\n follow: bool,\n globs: ignore::overrides::Override,\n heading: bool,\n hidden: bool,\n hyperlink_config: grep::printer::HyperlinkConfig,\n ignore_file_case_insensitive: bool,\n ignore_file: Vec,\n include_zero: bool,\n index: usize,\n invert_match: bool,\n is_terminal_stdout: bool,\n line_number: bool,\n max_columns: Option,\n max_columns_preview: bool,\n max_count: Option,\n max_depth: Option,\n max_filesize: Option,\n mmap_choice: grep::searcher::MmapChoice,\n mode: Mode,\n multiline: bool,\n multiline_dotall: bool,\n no_ig"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":114,"symbol":"from_low_args","kind":"function","lang":"rust","doc":"Convert low level arguments into high level arguments. This process can fail for a variety of reasons. For example, invalid globs or some kind of environment issue.","code":"pub(crate) fn from_low_args(mut low: LowArgs) -> anyhow::Result {\n // Callers should not be trying to convert low-level arguments when\n // a short-circuiting special mode is present.\n assert_eq!(None, low.special, \"special mode demands short-circuiting\");\n // If the sorting mode isn't supported, then we bail loudly. I'm not\n // sure if this is the right thing to do. We could silently \"not sort\"\n // as well. If we wanted to go that route, then we could just set\n // `low.sort = None` if `supported()` returns an error.\n if let Some(ref sort) = low.sort {\n sort.supported()?;\n }\n // We aggressively ban things from indexing at present.\n if (low.index > 0 || matches!(low.mode, Mode::Index(_)))\n && let Some(flag) = low.indexing_unsupported_flag()\n {\n anyhow::bail!(\n \"flag --{} does not support indexing\",\n flag.name_long()\n );\n }\n\n // We modify the mode in-place on `low` so that subsequent conversions\n // see the correct mode.\n match low.mode {\n Mode::Search(ref mut mode) => match *mode {\n"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":342,"symbol":"buffer_writer","kind":"function","lang":"rust","doc":"This is intended to be used from multiple threads. Namely, a buffer writer can create new buffers that are sent to threads. Threads can then independently write to the buffers. Once a unit of work is complete, a buffer can be given to the buffer writer to write to stdout.","code":"pub(crate) fn buffer_writer(&self) -> termcolor::BufferWriter {\n let mut wtr =\n termcolor::BufferWriter::stdout(self.color.to_termcolor());\n wtr.separator(self.file_separator.clone());\n wtr\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":360,"symbol":"has_implicit_path","kind":"function","lang":"rust","doc":"leading `./`), it's also useful to know for diagnostic reasons. For example, ripgrep will print an error message when nothing is searched since it's possible the ignore rules in play are too aggressive. But this warning is only emitted when ripgrep was called without any explicit file paths since otherwise the warning would likely be too aggressive.","code":"pub(crate) fn has_implicit_path(&self) -> bool {\n self.paths.has_implicit_path\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":368,"symbol":"haystack_builder","kind":"function","lang":"rust","doc":"Return a properly configured builder for constructing haystacks. The builder can be used to turn a directory entry (from the `ignore` crate) into something that can be searched.","code":"pub(crate) fn haystack_builder(&self) -> HaystackBuilder {\n let mut builder = HaystackBuilder::new();\n builder.strip_dot_prefix(self.paths.has_implicit_path);\n builder\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":379,"symbol":"matcher","kind":"function","lang":"rust","doc":"Return the matcher that should be used for searching using the engine choice made by the user. If there was a problem building the matcher (e.g., a syntax error), then this returns an error.","code":"pub(crate) fn matcher(&self) -> anyhow::Result {\n match self.engine {\n EngineChoice::Default => match self.matcher_rust() {\n Ok(m) => Ok(m),\n Err(err) => {\n anyhow::bail!(suggest_other_engine(err.to_string()));\n }\n },\n EngineChoice::PCRE2 => Ok(self.matcher_pcre2()?),\n EngineChoice::Auto => {\n let rust_err = match self.matcher_rust() {\n Ok(m) => return Ok(m),\n Err(err) => err,\n };\n log::debug!(\n \"error building Rust regex in hybrid mode:\\n{rust_err}\",\n );\n\n let pcre_err = match self.matcher_pcre2() {\n Ok(m) => return Ok(m),\n Err(err) => err,\n };\n let divider = \"~\".repeat(79);\n anyhow::bail!(\n \"regex could not be compiled with either the default \\\n regex engine or with PCRE2.\\n\\n\\\n default regex engine error:\\n\\\n {divider}\\n\\\n {rust_err}\\n\\\n "} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":422,"symbol":"matcher_pcre2","kind":"function","lang":"rust","doc":"If there was a problem building the matcher (such as a regex syntax error), then an error is returned. If the `pcre2` feature is not enabled then this always returns an error.","code":"fn matcher_pcre2(&self) -> anyhow::Result {\n #[cfg(feature = \"pcre2\")]\n {\n let mut builder = grep::pcre2::RegexMatcherBuilder::new();\n builder.multi_line(true).fixed_strings(self.fixed_strings);\n match self.case {\n CaseMode::Sensitive => builder.caseless(false),\n CaseMode::Insensitive => builder.caseless(true),\n CaseMode::Smart => builder.case_smart(true),\n };\n if let Some(ref boundary) = self.boundary {\n match *boundary {\n BoundaryMode::Line => builder.whole_line(true),\n BoundaryMode::Word => builder.word(true),\n };\n }\n // For whatever reason, the JIT craps out during regex compilation with\n // a \"no more memory\" error on 32 bit systems. So don't use it there.\n if cfg!(target_pointer_width = \"64\") {\n builder\n .jit_if_available(true)\n // The PCRE2 docs say that 32KB is the default, and that 1MB\n // should be big enough for anything. But let's crank it to\n "} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":472,"symbol":"matcher_rust","kind":"function","lang":"rust","doc":"Build a matcher using Rust's regex engine. If there was a problem building the matcher (such as a regex syntax error), then an error is returned.","code":"fn matcher_rust(&self) -> anyhow::Result {\n let mut builder = grep::regex::RegexMatcherBuilder::new();\n builder\n .multi_line(true)\n .unicode(!self.no_unicode)\n .octal(false)\n .fixed_strings(self.fixed_strings);\n match self.case {\n CaseMode::Sensitive => builder.case_insensitive(false),\n CaseMode::Insensitive => builder.case_insensitive(true),\n CaseMode::Smart => builder.case_smart(true),\n };\n if let Some(ref boundary) = self.boundary {\n match *boundary {\n BoundaryMode::Line => builder.whole_line(true),\n BoundaryMode::Word => builder.word(true),\n };\n }\n if self.multiline {\n builder.dot_matches_new_line(self.multiline_dotall);\n if self.crlf {\n builder.crlf(true).line_terminator(None);\n }\n } else {\n builder.line_terminator(Some(b'\\n')).dot_matches_new_line(false);\n if self.crlf {\n builder.crlf(true);\n }\n // We don't need to set this in multiline mode since multiline\n // m"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":532,"symbol":"matches_possible","kind":"function","lang":"rust","doc":"Returns true if some non-zero number of matches is believed to be possible. When this returns false, it is impossible for ripgrep to ever report a match.","code":"pub(crate) fn matches_possible(&self) -> bool {\n if self.patterns.patterns.is_empty() && !self.invert_match {\n return false;\n }\n if self.max_count == Some(0) {\n return false;\n }\n true\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":547,"symbol":"mode","kind":"function","lang":"rust","doc":"Returns the \"mode\" that ripgrep should operate in. This is generally useful for determining what action ripgrep should take. The main mode is of course to \"search,\" but there are other non-search modes such as `--type-list` and `--files`.","code":"pub(crate) fn mode(&self) -> Mode {\n self.mode\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":556,"symbol":"path_printer_builder","kind":"function","lang":"rust","doc":"Returns a builder for constructing a \"path printer.\" This is useful for the `--files` mode in ripgrep, where the printer just needs to emit paths and not need to worry about the functionality of searching.","code":"pub(crate) fn path_printer_builder(\n &self,\n ) -> grep::printer::PathPrinterBuilder {\n let mut builder = grep::printer::PathPrinterBuilder::new();\n builder\n .color_specs(self.colors.clone())\n .hyperlink(self.hyperlink_config.clone())\n .separator(self.path_separator.clone())\n .terminator(self.path_terminator.unwrap_or(b'\\n'));\n builder\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":572,"symbol":"printer","kind":"function","lang":"rust","doc":"Returns a printer for the given search mode. This chooses which printer to build (JSON, summary or standard) based on the search mode given.","code":"pub(crate) fn printer(\n &self,\n search_mode: SearchMode,\n wtr: W,\n ) -> Printer {\n let summary_kind = if self.quiet {\n match search_mode {\n SearchMode::FilesWithMatches\n | SearchMode::Count\n | SearchMode::CountMatches\n | SearchMode::JSON\n | SearchMode::Standard => SummaryKind::QuietWithMatch,\n SearchMode::FilesWithoutMatch => {\n SummaryKind::QuietWithoutMatch\n }\n }\n } else {\n match search_mode {\n SearchMode::FilesWithMatches => SummaryKind::PathWithMatch,\n SearchMode::FilesWithoutMatch => SummaryKind::PathWithoutMatch,\n SearchMode::Count => SummaryKind::Count,\n SearchMode::CountMatches => SummaryKind::CountMatches,\n SearchMode::JSON => {\n return Printer::JSON(self.printer_json(wtr));\n }\n SearchMode::Standard => {\n return Printer::Standard(self.printer_standard(wtr));\n }\n }\n };\n Prin"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":606,"symbol":"printer_json","kind":"function","lang":"rust","doc":"Builds a JSON printer.","code":"fn printer_json(\n &self,\n wtr: W,\n ) -> grep::printer::JSON {\n grep::printer::JSONBuilder::new()\n .pretty(false)\n .always_begin_end(false)\n .replacement(self.replace.clone().map(|r| r.into()))\n .build(wtr)\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":619,"symbol":"printer_standard","kind":"function","lang":"rust","doc":"Builds a \"standard\" grep printer where matches are printed as plain text lines.","code":"fn printer_standard(\n &self,\n wtr: W,\n ) -> grep::printer::Standard {\n let mut builder = grep::printer::StandardBuilder::new();\n builder\n .byte_offset(self.byte_offset)\n .color_specs(self.colors.clone())\n .column(self.column)\n .heading(self.heading)\n .hyperlink(self.hyperlink_config.clone())\n .max_columns_preview(self.max_columns_preview)\n .max_columns(self.max_columns)\n .only_matching(self.only_matching)\n .path(self.with_filename)\n .path_terminator(self.path_terminator.clone())\n .per_match_one_line(true)\n .per_match(self.vimgrep)\n .replacement(self.replace.clone().map(|r| r.into()))\n .separator_context(self.context_separator.clone().into_bytes())\n .separator_field_context(\n self.field_context_separator.clone().into_bytes(),\n )\n .separator_field_match(\n self.field_match_separator.clone().into_bytes(),\n )\n .separator_path(self.path_separator.clone())\n .stats(self.stats.is_some()"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":661,"symbol":"printer_summary","kind":"function","lang":"rust","doc":"Builds a \"summary\" printer where search results are aggregated on a file-by-file basis.","code":"fn printer_summary(\n &self,\n wtr: W,\n kind: SummaryKind,\n ) -> grep::printer::Summary {\n grep::printer::SummaryBuilder::new()\n .color_specs(self.colors.clone())\n .exclude_zero(!self.include_zero)\n .hyperlink(self.hyperlink_config.clone())\n .kind(kind)\n .path(self.with_filename)\n .path_terminator(self.path_terminator.clone())\n .separator_field(b\":\".to_vec())\n .separator_path(self.path_separator.clone())\n .stats(self.stats.is_some())\n .build(wtr)\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":685,"symbol":"quiet","kind":"function","lang":"rust","doc":"Returns true if ripgrep should operate in \"quiet\" mode. Generally speaking, quiet mode means that ripgrep should not print anything to stdout. There are some exceptions. For example, when the user has provided `--stats`, then ripgrep will print statistics to stdout.","code":"pub(crate) fn quiet(&self) -> bool {\n self.quiet\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":697,"symbol":"quit_after_match","kind":"function","lang":"rust","doc":"This is useful for example when quiet mode is enabled. In that case, users generally can't tell the difference in behavior between a search that finds all matches and a search that only finds one of them. (An exception here is if `--stats` is given, then `quit_after_match` will always return false since the user expects ripgrep to find everything.)","code":"pub(crate) fn quit_after_match(&self) -> bool {\n self.quit_after_match\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":705,"symbol":"search_worker","kind":"function","lang":"rust","doc":"Build a worker for executing searches. Search results are found using the given matcher and written to the given printer.","code":"pub(crate) fn search_worker(\n &self,\n matcher: PatternMatcher,\n searcher: grep::searcher::Searcher,\n printer: Printer,\n ) -> anyhow::Result> {\n let mut builder = SearchWorkerBuilder::new();\n builder\n .preprocessor(self.pre.clone())?\n .preprocessor_globs(self.pre_globs.clone())\n .search_zip(self.search_zip)\n .binary_detection_explicit(self.binary.explicit.clone())\n .binary_detection_implicit(self.binary.implicit.clone());\n Ok(builder.build(matcher, searcher, printer))\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":722,"symbol":"searcher","kind":"function","lang":"rust","doc":"Build a searcher from the command line parameters.","code":"pub(crate) fn searcher(&self) -> anyhow::Result {\n let line_term = if self.crlf {\n grep::matcher::LineTerminator::crlf()\n } else if self.null_data {\n grep::matcher::LineTerminator::byte(b'\\x00')\n } else {\n grep::matcher::LineTerminator::byte(b'\\n')\n };\n let mut builder = grep::searcher::SearcherBuilder::new();\n builder\n .max_matches(self.max_count)\n .line_terminator(line_term)\n .invert_match(self.invert_match)\n .line_number(self.line_number)\n .multi_line(self.multiline)\n .memory_map(self.mmap_choice.clone())\n .stop_on_nonmatch(self.stop_on_nonmatch);\n match self.context {\n ContextMode::Passthru => {\n builder.passthru(true);\n }\n ContextMode::Limited(ref limited) => {\n let (before, after) = limited.get();\n builder.before_context(before);\n builder.after_context(after);\n }\n }\n match self.encoding {\n EncodingMode::Auto => {} // default for the searcher\n EncodingMode::"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":773,"symbol":"sort","kind":"function","lang":"rust","doc":"Once special case is when sorting by path in ascending order has been requested. In this case, the iterator given is returned as is without any additional sorting. This is done because `walk_builder()` will sort the iterator it yields during directory traversal, so no additional sorting is needed.","code":"pub(crate) fn sort<'a, I>(\n &self,\n haystacks: I,\n ) -> Box + 'a>\n where\n I: Iterator + 'a,\n {\n use std::{cmp::Ordering, fs::Metadata, io, time::SystemTime};\n\n fn attach_timestamps(\n haystacks: impl Iterator,\n get: impl Fn(&Metadata) -> io::Result,\n ) -> impl Iterator)> {\n haystacks.map(move |s| {\n let time = s.path().metadata().and_then(|m| get(&m)).ok();\n (s, time)\n })\n }\n\n let Some(ref sort) = self.sort else { return Box::new(haystacks) };\n let mut with_timestamps: Vec<_> = match sort.kind {\n SortModeKind::Path if !sort.reverse => return Box::new(haystacks),\n SortModeKind::Path => {\n let mut haystacks = haystacks.collect::>();\n haystacks.sort_by(|ref h1, ref h2| {\n h1.path().cmp(h2.path()).reverse()\n });\n return Box::new(haystacks.into_iter());\n }\n SortModeKind::LastModified => {\n "} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":782,"symbol":"attach_timestamps","kind":"function","lang":"rust","code":"fn attach_timestamps(\n haystacks: impl Iterator,\n get: impl Fn(&Metadata) -> io::Result,\n ) -> impl Iterator)> {\n haystacks.map(move |s| {\n let time = s.path().metadata().and_then(|m| get(&m)).ok();\n (s, time)\n })\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":833,"symbol":"stats","kind":"function","lang":"rust","doc":"Returns a stats object if the user requested that ripgrep keep track of various metrics during a search. When this returns `None`, then callers may assume that the user did not request statistics.","code":"pub(crate) fn stats(&self) -> Option {\n self.stats.clone()\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":842,"symbol":"stdout","kind":"function","lang":"rust","doc":"Returns a color-enabled writer for stdout. The writer returned is also configured to do either line or block buffering, based on either explicit configuration from the user via CLI flags, or automatically based on whether stdout is connected to a tty.","code":"pub(crate) fn stdout(&self) -> grep::cli::StandardStream {\n let color = self.color.to_termcolor();\n match self.buffer {\n BufferMode::Auto => {\n if self.is_terminal_stdout {\n grep::cli::stdout_buffered_line(color)\n } else {\n grep::cli::stdout_buffered_block(color)\n }\n }\n BufferMode::Line => grep::cli::stdout_buffered_line(color),\n BufferMode::Block => grep::cli::stdout_buffered_block(color),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":864,"symbol":"threads","kind":"function","lang":"rust","doc":"search. This number is the result of reasoning about both heuristics (like the available number of cores) and whether ripgrep's mode supports parallelism. It is intended that this number be used to directly determine how many threads to spawn.","code":"pub(crate) fn threads(&self) -> usize {\n self.threads\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":872,"symbol":"types","kind":"function","lang":"rust","doc":"Returns the file type matcher that was built. The matcher includes both the default rules and any rules added by the user for this specific invocation.","code":"pub(crate) fn types(&self) -> &ignore::types::Types {\n &self.types\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":885,"symbol":"walk_builder","kind":"function","lang":"rust","doc":"threaded directory traversal. For multi threaded traversal, the number of threads configured is equivalent to `HiArgs::threads`. If `HiArgs::threads` is equal to `1`, then callers should generally choose to explicitly use single threaded traversal since it won't have the unnecessary overhead of synchronization.","code":"pub(crate) fn walk_builder(&self) -> anyhow::Result {\n let mut builder = ignore::WalkBuilder::new(&self.paths.paths[0]);\n for path in self.paths.paths.iter().skip(1) {\n builder.add(path);\n }\n if !self.no_ignore_files {\n for path in self.ignore_file.iter() {\n if let Some(err) = builder.add_ignore(path) {\n ignore_message!(\"{err}\");\n }\n }\n }\n builder\n .max_depth(self.max_depth)\n .follow_links(self.follow)\n .max_filesize(self.max_filesize)\n .threads(self.threads)\n .same_file_system(self.one_file_system)\n .skip_stdout(matches!(self.mode, Mode::Search(_)))\n .overrides(self.globs.clone())\n .types(self.types.clone())\n .hidden(!self.hidden)\n .parents(!self.no_ignore_parent)\n .ignore(!self.no_ignore_dot)\n .git_global(!self.no_ignore_vcs && !self.no_ignore_global)\n .git_ignore(!self.no_ignore_vcs)\n .git_exclude(!self.no_ignore_vcs && !self.no_ignore_exclude)\n .require_git(!self.no_require"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":931,"symbol":"index","kind":"function","lang":"rust","code":"pub(crate) fn index(&self) -> usize {\n self.index\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":936,"symbol":"index_write","kind":"function","lang":"rust","code":"pub(crate) fn index_write(&self) -> anyhow::Result {\n let index = grep_index::IndexDiscovery::new()\n .create(true)\n .discover()?\n .ok_or_else(|| {\n anyhow::anyhow!(\n \"failed to find a place to create/update an index\"\n )\n })?;\n Ok(index)\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":949,"symbol":"index_read","kind":"function","lang":"rust","code":"pub(crate) fn index_read(&self) -> anyhow::Result {\n let index = grep_index::IndexDiscovery::new().discover()?.ok_or_else(\n || anyhow::anyhow!(\"failed to find an index to read\"),\n )?;\n Ok(index)\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":968,"symbol":"State","kind":"type","lang":"rust","doc":"conversions as a way to communicate changes to other conversions. For example, reading patterns might consume from stdin. If we know stdin has been consumed and no other file paths have been given, then we know for sure that we should search the CWD. In this way, a state change when reading the patterns can impact how the file paths are ultimately generated.","code":"struct State {\n /// Whether it's believed that tty is connected to stdout. Note that on\n /// unix systems, this is always correct. On Windows, heuristics are used\n /// by Rust's standard library, particularly for cygwin/MSYS environments.\n is_terminal_stdout: bool,\n /// Whether stdin has already been consumed. This is useful to know and for\n /// providing good error messages when the user has tried to read from stdin\n /// in two different places. For example, `rg -f - -`.\n stdin_consumed: bool,\n /// The current working directory.\n cwd: PathBuf,\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":986,"symbol":"new","kind":"function","lang":"rust","doc":"Initialize state to some sensible defaults. Note that the state values may change throughout the lifetime of argument parsing.","code":"fn new() -> anyhow::Result {\n use std::io::IsTerminal;\n\n let cwd = current_dir()?;\n log::debug!(\"read CWD from environment: {}\", cwd.display());\n Ok(State {\n is_terminal_stdout: std::io::stdout().is_terminal(),\n stdin_consumed: false,\n cwd,\n })\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1003,"symbol":"Patterns","kind":"type","lang":"rust","doc":"The disjunction of patterns to search for. The number of patterns can be empty, e.g., via `-f /dev/null`.","code":"struct Patterns {\n /// The actual patterns to match.\n patterns: Vec,\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1016,"symbol":"from_low_args","kind":"function","lang":"rust","doc":"This includes collecting patterns from -e/--regexp and -f/--file. If the invocation implies that the first positional argument is a pattern (the common case), then the first positional argument is extracted as well.","code":"fn from_low_args(\n state: &mut State,\n low: &mut LowArgs,\n ) -> anyhow::Result {\n // The first positional is only a pattern when ripgrep is instructed to\n // search and neither -e/--regexp nor -f/--file is given. Basically,\n // the first positional is a pattern only when a pattern hasn't been\n // given in some other way.\n\n // No search means no patterns. Even if -e/--regexp or -f/--file is\n // given, we know we won't use them so don't bother collecting them.\n if !matches!(low.mode, Mode::Search(_)) {\n return Ok(Patterns { patterns: vec![] });\n }\n // If we got nothing from -e/--regexp and -f/--file, then the first\n // positional is a pattern.\n if low.patterns.is_empty() {\n anyhow::ensure!(\n !low.positional.is_empty(),\n \"ripgrep requires at least one pattern to execute a search\"\n );\n let ospat = low.positional.remove(0);\n let Ok(pat) = ospat.into_string() else {\n anyhow::bail!(\"pattern given is not valid UTF-8\")\n };\n return Ok(Patterns { patterns: vec![pat] });\n"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1091,"symbol":"Paths","kind":"type","lang":"rust","doc":"The collection of paths we want to search for. This guarantees that there is always at least one path.","code":"struct Paths {\n /// The actual paths.\n paths: Vec,\n /// This is true when ripgrep had to guess to search the current working\n /// directory. e.g., When the user just runs `rg foo`. It is odd to need\n /// this, but it subtly changes how the paths are printed. When no explicit\n /// path is given, then ripgrep doesn't prefix each path with `./`. But\n /// otherwise it does! This curious behavior matches what GNU grep does.\n has_implicit_path: bool,\n /// Set to true if it is known that only a single file descriptor will\n /// be searched.\n is_one_file: bool,\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1107,"symbol":"from_low_args","kind":"function","lang":"rust","doc":"Drain the search paths out of the given low arguments.","code":"fn from_low_args(\n state: &mut State,\n _: &Patterns,\n low: &mut LowArgs,\n ) -> anyhow::Result {\n // We require a `&Patterns` even though we don't use it to ensure that\n // patterns have already been read from LowArgs. This let's us safely\n // assume that all remaining positional arguments are intended to be\n // file paths.\n\n let mut paths = Vec::with_capacity(low.positional.len());\n for osarg in low.positional.drain(..) {\n let path = PathBuf::from(osarg);\n if state.stdin_consumed && path == Path::new(\"-\") {\n anyhow::bail!(\n \"error: attempted to read patterns from stdin \\\n while also searching stdin\",\n );\n }\n paths.push(path);\n }\n log::debug!(\"number of paths given to search: {}\", paths.len());\n if !paths.is_empty() {\n let is_one_file = paths.len() == 1\n // Note that we specifically use `!paths[0].is_dir()` here\n // instead of `paths[0].is_file()`. Namely, the latter can\n // return `false` even when the path is something res"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1173,"symbol":"is_only_stdin","kind":"function","lang":"rust","doc":"Returns true if ripgrep will only search stdin and nothing else.","code":"fn is_only_stdin(&self) -> bool {\n self.paths.len() == 1 && self.paths[0] == Path::new(\"-\")\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1188,"symbol":"BinaryDetection","kind":"type","lang":"rust","doc":"on whether a file is explicitly being searched (e.g., via a CLI argument) or implicitly searched (e.g., via directory traversal). In general, the former can never use a heuristic that lets it \"quit\" searching before either getting EOF or finding a match. (Because doing otherwise would be considered a filter, and ripgrep follows the rule that an explicitly given file is always searched.)","code":"struct BinaryDetection {\n explicit: grep::searcher::BinaryDetection,\n implicit: grep::searcher::BinaryDetection,\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1195,"symbol":"from_low_args","kind":"function","lang":"rust","doc":"Determines the correct binary detection mode from low-level arguments.","code":"fn from_low_args(_: &State, low: &LowArgs) -> BinaryDetection {\n let none = matches!(low.binary, BinaryMode::AsText) || low.null_data;\n let convert = matches!(low.binary, BinaryMode::SearchAndSuppress);\n let explicit = if none {\n grep::searcher::BinaryDetection::none()\n } else {\n grep::searcher::BinaryDetection::convert(b'\\x00')\n };\n let implicit = if none {\n grep::searcher::BinaryDetection::none()\n } else if convert {\n grep::searcher::BinaryDetection::convert(b'\\x00')\n } else {\n grep::searcher::BinaryDetection::quit(b'\\x00')\n };\n BinaryDetection { explicit, implicit }\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1215,"symbol":"is_none","kind":"function","lang":"rust","doc":"Returns true when both implicit and explicit binary detection is disabled.","code":"pub(crate) fn is_none(&self) -> bool {\n let none = grep::searcher::BinaryDetection::none();\n self.explicit == none && self.implicit == none\n }"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1222,"symbol":"types","kind":"function","lang":"rust","doc":"Builds the file type matcher from low level arguments.","code":"fn types(low: &LowArgs) -> anyhow::Result {\n let mut builder = ignore::types::TypesBuilder::new();\n builder.add_defaults();\n for tychange in low.type_changes.iter() {\n match *tychange {\n TypeChange::Clear { ref name } => {\n builder.clear(name);\n }\n TypeChange::Add { ref def } => {\n builder.add_def(def)?;\n }\n TypeChange::Select { ref name } => {\n builder.select(name);\n }\n TypeChange::Negate { ref name } => {\n builder.negate(name);\n }\n }\n }\n Ok(builder.build()?)\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1246,"symbol":"globs","kind":"function","lang":"rust","doc":"Builds the glob \"override\" matcher from the CLI `-g/--glob` and `--iglob` flags.","code":"fn globs(\n state: &State,\n low: &LowArgs,\n) -> anyhow::Result {\n if low.globs.is_empty() && low.iglobs.is_empty() {\n return Ok(ignore::overrides::Override::empty());\n }\n let mut builder = ignore::overrides::OverrideBuilder::new(&state.cwd);\n // Make all globs case insensitive with --glob-case-insensitive.\n if low.glob_case_insensitive {\n builder.case_insensitive(true).unwrap();\n }\n for glob in low.globs.iter() {\n builder.add(glob)?;\n }\n // This only enables case insensitivity for subsequent globs.\n builder.case_insensitive(true).unwrap();\n for glob in low.iglobs.iter() {\n builder.add(&glob)?;\n }\n Ok(builder.build()?)\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1270,"symbol":"preprocessor_globs","kind":"function","lang":"rust","doc":"Builds a glob matcher for all of the preprocessor globs (via `--pre-glob`).","code":"fn preprocessor_globs(\n state: &State,\n low: &LowArgs,\n) -> anyhow::Result {\n if low.pre_glob.is_empty() {\n return Ok(ignore::overrides::Override::empty());\n }\n let mut builder = ignore::overrides::OverrideBuilder::new(&state.cwd);\n for glob in low.pre_glob.iter() {\n builder.add(glob)?;\n }\n Ok(builder.build()?)\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1286,"symbol":"stats","kind":"function","lang":"rust","doc":"Determines whether stats should be tracked for this search. If so, a stats object is returned.","code":"fn stats(low: &LowArgs) -> Option {\n if !matches!(low.mode, Mode::Search(_)) {\n return None;\n }\n if low.stats || matches!(low.mode, Mode::Search(SearchMode::JSON)) {\n return Some(grep::printer::Stats::new());\n }\n None\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1298,"symbol":"take_color_specs","kind":"function","lang":"rust","doc":"Pulls out any color specs provided by the user and assembles them into one single configuration.","code":"fn take_color_specs(_: &mut State, low: &mut LowArgs) -> ColorSpecs {\n let mut specs = grep::printer::default_color_specs();\n for spec in low.colors.drain(..) {\n specs.push(spec);\n }\n ColorSpecs::new(&specs)\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1308,"symbol":"take_hyperlink_config","kind":"function","lang":"rust","doc":"Pulls out the necessary info from the low arguments to build a full hyperlink configuration.","code":"fn take_hyperlink_config(\n _: &mut State,\n low: &mut LowArgs,\n) -> anyhow::Result {\n let mut env = grep::printer::HyperlinkEnvironment::new();\n if let Some(hostname) = hostname(low.hostname_bin.as_deref()) {\n log::debug!(\"found hostname for hyperlink configuration: {hostname}\");\n env.host(Some(hostname));\n }\n if let Some(wsl_prefix) = wsl_prefix() {\n log::debug!(\n \"found wsl_prefix for hyperlink configuration: {wsl_prefix}\"\n );\n env.wsl_prefix(Some(wsl_prefix));\n }\n let fmt = std::mem::take(&mut low.hyperlink_format);\n log::debug!(\"hyperlink format: {:?}\", fmt.to_string());\n Ok(grep::printer::HyperlinkConfig::new(env, fmt))\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1334,"symbol":"current_dir","kind":"function","lang":"rust","doc":"Attempts to discover the current working directory. This mostly just defers to the standard library, however, such things will fail if ripgrep is in a directory that no longer exists. We attempt some fallback mechanisms, such as querying the PWD environment variable, but otherwise return an error.","code":"fn current_dir() -> anyhow::Result {\n let err = match std::env::current_dir() {\n Err(err) => err,\n Ok(cwd) => return Ok(cwd),\n };\n if let Some(cwd) = std::env::var_os(\"PWD\") {\n if !cwd.is_empty() {\n return Ok(PathBuf::from(cwd));\n }\n }\n anyhow::bail!(\n \"failed to get current working directory: {err}\\n\\\n did your CWD get deleted?\",\n )\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1361,"symbol":"hostname","kind":"function","lang":"rust","doc":"no arguments) to get the hostname after trimming leading and trailing whitespace. If that fails for any reason, then it falls back to getting the hostname via platform specific means (e.g., `gethostname` on Unix). The purpose of `bin` is to make it possible for end users to override how ripgrep determines the hostname.","code":"fn hostname(bin: Option<&Path>) -> Option {\n let Some(bin) = bin else { return platform_hostname() };\n let bin = match grep::cli::resolve_binary(bin) {\n Ok(bin) => bin,\n Err(err) => {\n log::debug!(\n \"failed to run command '{bin:?}' to get hostname \\\n (falling back to platform hostname): {err}\",\n );\n return platform_hostname();\n }\n };\n let mut cmd = std::process::Command::new(&bin);\n cmd.stdin(std::process::Stdio::null());\n let rdr = match grep::cli::CommandReader::new(&mut cmd) {\n Ok(rdr) => rdr,\n Err(err) => {\n log::debug!(\n \"failed to spawn command '{bin:?}' to get \\\n hostname (falling back to platform hostname): {err}\",\n );\n return platform_hostname();\n }\n };\n let out = match std::io::read_to_string(rdr) {\n Ok(out) => out,\n Err(err) => {\n log::debug!(\n \"failed to read output from command '{bin:?}' to get \\\n hostname (falling back to platform hostname): {err}\",\n );\n return platform_hostname();\n }\n "} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1411,"symbol":"platform_hostname","kind":"function","lang":"rust","doc":"Attempts to get the hostname by using platform specific routines. For example, this will do `gethostname` on Unix and `GetComputerNameExW` on Windows.","code":"fn platform_hostname() -> Option {\n let hostname_os = match grep::cli::hostname() {\n Ok(x) => x,\n Err(err) => {\n log::debug!(\"could not get hostname: {}\", err);\n return None;\n }\n };\n let Some(hostname) = hostname_os.to_str() else {\n log::debug!(\n \"got hostname {:?}, but it's not valid UTF-8\",\n hostname_os\n );\n return None;\n };\n Some(hostname.to_string())\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1438,"symbol":"wsl_prefix","kind":"function","lang":"rust","doc":"applications to open files stored within a WSL drive. If a WSL distro name is unavailable, not valid UTF-8 or this isn't running in a Unix environment, then this returns None. See: ","code":"fn wsl_prefix() -> Option {\n if !cfg!(unix) {\n return None;\n }\n let distro_os = std::env::var_os(\"WSL_DISTRO_NAME\")?;\n let Some(distro) = distro_os.to_str() else {\n log::debug!(\n \"found WSL_DISTRO_NAME={:?}, but value is not UTF-8\",\n distro_os\n );\n return None;\n };\n Some(format!(\"wsl$/{distro}\"))\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1458,"symbol":"suggest_other_engine","kind":"function","lang":"rust","doc":"Possibly suggest another regex engine based on the error message given. This inspects an error resulting from building a Rust regex matcher, and if it's believed to correspond to a syntax error that another engine could handle, then add a message to suggest the use of the engine flag.","code":"fn suggest_other_engine(msg: String) -> String {\n if let Some(pcre_msg) = suggest_pcre2(&msg) {\n return pcre_msg;\n }\n msg\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1470,"symbol":"suggest_pcre2","kind":"function","lang":"rust","doc":"Possibly suggest PCRE2 based on the error message given. Inspect an error resulting from building a Rust regex matcher, and if it's believed to correspond to a syntax error that PCRE2 could handle, then add a message to suggest the use of -P/--pcre2.","code":"fn suggest_pcre2(msg: &str) -> Option {\n if !cfg!(feature = \"pcre2\") {\n return None;\n }\n if !msg.contains(\"backreferences\") && !msg.contains(\"look-around\") {\n None\n } else {\n Some(format!(\n \"{msg}\n\nConsider enabling PCRE2 with the --pcre2 flag, which can handle backreferences\nand look-around.\",\n ))\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1491,"symbol":"suggest_multiline","kind":"function","lang":"rust","doc":"Possibly suggest multiline mode based on the error message given. Does a bit of a hacky inspection of the given error message, and if it looks like the user tried to type a literal line terminator then it will return a new error message suggesting the use of -U/--multiline.","code":"fn suggest_multiline(msg: String) -> String {\n if msg.contains(\"the literal\") && msg.contains(\"not allowed\") {\n format!(\n \"{msg}\n\nConsider enabling multiline mode with the --multiline flag (or -U for short).\nWhen multiline mode is enabled, new line characters can be matched.\",\n )\n } else {\n msg\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/hiargs.rs","line":1505,"symbol":"suggest_text","kind":"function","lang":"rust","doc":"Possibly suggest the `-a/--text` flag.","code":"fn suggest_text(msg: String) -> String {\n if msg.contains(\"pattern contains \\\"\\\\0\\\"\") {\n format!(\n \"{msg}\n\nConsider enabling text mode with the --text flag (or -a for short). Otherwise,\nbinary detection is enabled and matching a NUL byte is impossible.\",\n )\n } else {\n msg\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":33,"symbol":"LowArgs","kind":"type","lang":"rust","doc":"`HyperlinkConfig`, since in order to get a full configuration, one needs to discover the hostname of the current system (which might require running a binary or a syscall). Low level arguments are populated by the parser directly via the `update` method on the corresponding implementation of the `Flag` trait.","code":"pub(crate) struct LowArgs {\n // Essential arguments.\n pub(crate) special: Option,\n pub(crate) mode: Mode,\n pub(crate) positional: Vec,\n pub(crate) patterns: Vec,\n // Everything else, sorted lexicographically.\n pub(crate) binary: BinaryMode,\n pub(crate) boundary: Option,\n pub(crate) buffer: BufferMode,\n pub(crate) byte_offset: bool,\n pub(crate) case: CaseMode,\n pub(crate) color: ColorChoice,\n pub(crate) colors: Vec,\n pub(crate) column: Option,\n pub(crate) context: ContextMode,\n pub(crate) context_separator: ContextSeparator,\n pub(crate) crlf: bool,\n pub(crate) dfa_size_limit: Option,\n pub(crate) encoding: EncodingMode,\n pub(crate) engine: EngineChoice,\n pub(crate) field_context_separator: FieldContextSeparator,\n pub(crate) field_match_separator: FieldMatchSeparator,\n pub(crate) fixed_strings: bool,\n pub(crate) follow: bool,\n pub(crate) glob_case_insensitive: bool,\n pub(crate) globs: Vec,\n pub(crate) heading: Option,\n pub(crate) hidden: bool,\n pub(crate) hostname_bin: Option,\n pub(crate) hyperl"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":125,"symbol":"SpecialMode","kind":"type","lang":"rust","doc":"ripgrep to short-circuit. In particular, we avoid converting low-level argument types into higher level arguments types that can fail for various reasons related to the environment. (Parsing the low-level arguments can fail too, but usually not in a way that can't be worked around by removing the corresponding arguments from the CLI command.) This is overall a hedge to ensure that version and help information are basically always available.","code":"pub(crate) enum SpecialMode {\n /// Show a condensed version of \"help\" output. Generally speaking, this\n /// shows each flag and an extremely terse description of that flag on\n /// a single line. This corresponds to the `-h` flag.\n HelpShort,\n /// Shows a very verbose version of the \"help\" output. The docs for some\n /// flags will be paragraphs long. This corresponds to the `--help` flag.\n HelpLong,\n /// Show condensed version information. e.g., `ripgrep x.y.z`.\n VersionShort,\n /// Show verbose version information. Includes \"short\" information as well\n /// as features included in the build.\n VersionLong,\n /// Show PCRE2's version information, or an error if this version of\n /// ripgrep wasn't compiled with PCRE2 support.\n VersionPCRE2,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":156,"symbol":"Mode","kind":"type","lang":"rust","doc":"exclusive and override one another. Note that -h/--help and -V/--version are not included in this because they always overrides everything else, regardless of where it appears in the command line. They are treated as \"special\" modes that short-circuit ripgrep's usual flow.","code":"pub(crate) enum Mode {\n /// ripgrep will execute a search of some kind.\n Search(SearchMode),\n /// Create or update a search index.\n Index(IndexMode),\n /// Show the files that *would* be searched, but don't actually search\n /// them.\n Files,\n /// List all file type definitions configured, including the default file\n /// types and any additional file types added to the command line.\n Types,\n /// Generate various things like the man page and completion files.\n Generate(GenerateMode),\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":172,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Mode {\n Mode::Search(SearchMode::Standard)\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":181,"symbol":"update","kind":"function","lang":"rust","doc":"Update this mode to the new mode while implementing various override semantics. For example, a search mode cannot override a non-search mode.","code":"pub(crate) fn update(&mut self, new: Mode) {\n match *self {\n // If we're in a search mode, then anything can override it.\n Mode::Search(_) => *self = new,\n _ => {\n // Once we're in a non-search mode, other non-search modes\n // can override it. But search modes cannot. So for example,\n // `--files -l` will still be Mode::Files.\n if !matches!(*self, Mode::Search(_)) {\n *self = new;\n }\n }\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":199,"symbol":"IndexMode","kind":"type","lang":"rust","doc":"The kind of index operation that ripgrep should perform.","code":"pub(crate) enum IndexMode {\n /// Add, update or remove files in an index.\n Crud,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":206,"symbol":"SearchMode","kind":"type","lang":"rust","doc":"The kind of search that ripgrep is going to perform.","code":"pub(crate) enum SearchMode {\n /// The default standard mode of operation. ripgrep looks for matches and\n /// prints them when found.\n ///\n /// There is no specific flag for this mode since it's the default. But\n /// some of the modes below, like JSON, have negation flags like --no-json\n /// that let you revert back to this default mode.\n Standard,\n /// Show files containing at least one match.\n FilesWithMatches,\n /// Show files that don't contain any matches.\n FilesWithoutMatch,\n /// Show files containing at least one match and the number of matching\n /// lines.\n Count,\n /// Show files containing at least one match and the total number of\n /// matches.\n CountMatches,\n /// Print matches in a JSON lines format.\n JSON,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":230,"symbol":"GenerateMode","kind":"type","lang":"rust","doc":"The thing to generate via the --generate flag.","code":"pub(crate) enum GenerateMode {\n /// Generate the raw roff used for the man page.\n Man,\n /// Completions for bash.\n CompleteBash,\n /// Completions for zsh.\n CompleteZsh,\n /// Completions for fish.\n CompleteFish,\n /// Completions for PowerShell.\n CompletePowerShell,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":245,"symbol":"BinaryMode","kind":"type","lang":"rust","doc":"Indicates how ripgrep should treat binary data.","code":"pub(crate) enum BinaryMode {\n /// Automatically determine the binary mode to use. Essentially, when\n /// a file is searched explicitly, then it will be searched using the\n /// `SearchAndSuppress` strategy. Otherwise, it will be searched in a way\n /// that attempts to skip binary files as much as possible. That is, once\n /// a file is classified as binary, searching will immediately stop.\n #[default]\n Auto,\n /// Search files even when they have binary data, but if a match is found,\n /// suppress it and emit a warning.\n ///\n /// In this mode, `NUL` bytes are replaced with line terminators. This is\n /// a heuristic meant to reduce heap memory usage, since true binary data\n /// isn't line oriented. If one attempts to treat such data as line\n /// oriented, then one may wind up with impractically large lines. For\n /// example, many binary files contain very long runs of NUL bytes.\n SearchAndSuppress,\n /// Treat all files as if they were plain text. There's no skipping and no\n /// replacement of `NUL` bytes with line terminators.\n AsText,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":269,"symbol":"BoundaryMode","kind":"type","lang":"rust","doc":"Indicates what kind of boundary mode to use (line or word).","code":"pub(crate) enum BoundaryMode {\n /// Only allow matches when surrounded by line boundaries.\n Line,\n /// Only allow matches when surrounded by word boundaries.\n Word,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":280,"symbol":"BufferMode","kind":"type","lang":"rust","doc":"Indicates the buffer mode that ripgrep should use when printing output. The default is `Auto`.","code":"pub(crate) enum BufferMode {\n /// Select the buffer mode, 'line' or 'block', automatically based on\n /// whether stdout is connected to a tty.\n #[default]\n Auto,\n /// Flush the output buffer whenever a line terminator is seen.\n ///\n /// This is useful when wants to see search results more immediately,\n /// for example, with `tail -f`.\n Line,\n /// Flush the output buffer whenever it reaches some fixed size. The size\n /// is usually big enough to hold many lines.\n ///\n /// This is useful for maximum performance, particularly when printing\n /// lots of results.\n Block,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":302,"symbol":"CaseMode","kind":"type","lang":"rust","doc":"Indicates the case mode for how to interpret all patterns given to ripgrep. The default is `Sensitive`.","code":"pub(crate) enum CaseMode {\n /// Patterns are matched case sensitively. i.e., `a` does not match `A`.\n #[default]\n Sensitive,\n /// Patterns are matched case insensitively. i.e., `a` does match `A`.\n Insensitive,\n /// Patterns are automatically matched case insensitively only when they\n /// consist of all lowercase literal characters. For example, the pattern\n /// `a` will match `A` but `A` will not match `a`.\n Smart,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":318,"symbol":"ColorChoice","kind":"type","lang":"rust","doc":"Indicates whether ripgrep should include color/hyperlinks in its output. The default is `Auto`.","code":"pub(crate) enum ColorChoice {\n /// Color and hyperlinks will never be used.\n Never,\n /// Color and hyperlinks will be used only when stdout is connected to a\n /// tty.\n #[default]\n Auto,\n /// Color will always be used.\n Always,\n /// Color will always be used and only ANSI escapes will be used.\n ///\n /// This only makes sense in the context of legacy Windows console APIs.\n /// At time of writing, ripgrep will try to use the legacy console APIs\n /// if ANSI coloring isn't believed to be possible. This option will force\n /// ripgrep to use ANSI coloring.\n Ansi,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":338,"symbol":"to_termcolor","kind":"function","lang":"rust","doc":"Convert this color choice to the corresponding termcolor type.","code":"pub(crate) fn to_termcolor(&self) -> termcolor::ColorChoice {\n match *self {\n ColorChoice::Never => termcolor::ColorChoice::Never,\n ColorChoice::Auto => termcolor::ColorChoice::Auto,\n ColorChoice::Always => termcolor::ColorChoice::Always,\n ColorChoice::Ansi => termcolor::ColorChoice::AlwaysAnsi,\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":352,"symbol":"ContextMode","kind":"type","lang":"rust","doc":"Indicates the line context options ripgrep should use for output. The default is no context at all.","code":"pub(crate) enum ContextMode {\n /// All lines will be printed. That is, the context is unbounded.\n Passthru,\n /// Only show a certain number of lines before and after each match.\n Limited(ContextModeLimited),\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":360,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> ContextMode {\n ContextMode::Limited(ContextModeLimited::default())\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":371,"symbol":"set_before","kind":"function","lang":"rust","doc":"Set the \"before\" context. If this was set to \"passthru\" context, then it is overridden in favor of limited context with the given value for \"before\" and `0` for \"after.\"","code":"pub(crate) fn set_before(&mut self, lines: usize) {\n match *self {\n ContextMode::Passthru => {\n *self = ContextMode::Limited(ContextModeLimited {\n before: Some(lines),\n after: None,\n both: None,\n })\n }\n ContextMode::Limited(ContextModeLimited {\n ref mut before,\n ..\n }) => *before = Some(lines),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":392,"symbol":"set_after","kind":"function","lang":"rust","doc":"Set the \"after\" context. If this was set to \"passthru\" context, then it is overridden in favor of limited context with the given value for \"after\" and `0` for \"before.\"","code":"pub(crate) fn set_after(&mut self, lines: usize) {\n match *self {\n ContextMode::Passthru => {\n *self = ContextMode::Limited(ContextModeLimited {\n before: None,\n after: Some(lines),\n both: None,\n })\n }\n ContextMode::Limited(ContextModeLimited {\n ref mut after, ..\n }) => *after = Some(lines),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":412,"symbol":"set_both","kind":"function","lang":"rust","doc":"Set the \"both\" context. If this was set to \"passthru\" context, then it is overridden in favor of limited context with the given value for \"both\" and `None` for \"before\" and \"after\".","code":"pub(crate) fn set_both(&mut self, lines: usize) {\n match *self {\n ContextMode::Passthru => {\n *self = ContextMode::Limited(ContextModeLimited {\n before: None,\n after: None,\n both: Some(lines),\n })\n }\n ContextMode::Limited(ContextModeLimited {\n ref mut both, ..\n }) => *both = Some(lines),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":430,"symbol":"get_limited","kind":"function","lang":"rust","doc":"A convenience function for use in tests that returns the limited context. If this mode isn't limited, then it panics.","code":"pub(crate) fn get_limited(&self) -> (usize, usize) {\n match *self {\n ContextMode::Passthru => unreachable!(\"context mode is passthru\"),\n ContextMode::Limited(ref limited) => limited.get(),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":452,"symbol":"ContextModeLimited","kind":"type","lang":"rust","doc":"the default value and occurs when no value is specified. `both` is only set by the -C/--context flag. The reason why we don't just set before = after = --context is because the before and after context settings always take precedent over the -C/--context setting, regardless of order. Thus, we need to keep track of them separately.","code":"pub(crate) struct ContextModeLimited {\n before: Option,\n after: Option,\n both: Option,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":464,"symbol":"get","kind":"function","lang":"rust","doc":"Returns the specific number of contextual lines that should be shown around each match. This takes proper precedent into account, i.e., that `before` and `after` both partially override `both` in all cases. By default, this returns `(0, 0)`.","code":"pub(crate) fn get(&self) -> (usize, usize) {\n let (mut before, mut after) =\n self.both.map(|lines| (lines, lines)).unwrap_or((0, 0));\n // --before and --after always override --context, regardless\n // of where they appear relative to each other.\n if let Some(lines) = self.before {\n before = lines;\n }\n if let Some(lines) = self.after {\n after = lines;\n }\n (before, after)\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":484,"symbol":"ContextSeparator","kind":"type","lang":"rust","doc":"Represents the separator to use between non-contiguous sections of contextual lines. The default is `--`.","code":"pub(crate) struct ContextSeparator(Option);"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":487,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> ContextSeparator {\n ContextSeparator(Some(BString::from(\"--\")))\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":495,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new context separator from the user provided argument. This handles unescaping.","code":"pub(crate) fn new(os: &OsStr) -> anyhow::Result {\n let Some(string) = os.to_str() else {\n anyhow::bail!(\n \"separator must be valid UTF-8 (use escape sequences \\\n to provide a separator that is not valid UTF-8)\"\n )\n };\n Ok(ContextSeparator(Some(Vec::unescape_bytes(string).into())))\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":507,"symbol":"disabled","kind":"function","lang":"rust","doc":"Creates a new separator that instructs the printer to disable contextual separators entirely.","code":"pub(crate) fn disabled() -> ContextSeparator {\n ContextSeparator(None)\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":516,"symbol":"into_bytes","kind":"function","lang":"rust","doc":"Return the raw bytes of this separator. If context separators were disabled, then this returns `None`. Note that this may return a `Some` variant with zero bytes.","code":"pub(crate) fn into_bytes(self) -> Option> {\n self.0.map(|sep| sep.into())\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":525,"symbol":"EncodingMode","kind":"type","lang":"rust","doc":"The encoding mode the searcher will use. The default is `Auto`.","code":"pub(crate) enum EncodingMode {\n /// Use only BOM sniffing to auto-detect an encoding.\n #[default]\n Auto,\n /// Use an explicit encoding forcefully, but let BOM sniffing override it.\n Some(grep::searcher::Encoding),\n /// Use no explicit encoding and disable all BOM sniffing. This will\n /// always result in searching the raw bytes, regardless of their\n /// true encoding.\n Disabled,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":541,"symbol":"EngineChoice","kind":"type","lang":"rust","doc":"The regex engine to use. The default is `Default`.","code":"pub(crate) enum EngineChoice {\n /// Uses the default regex engine: Rust's `regex` crate.\n ///\n /// (Well, technically it uses `regex-automata`, but `regex-automata` is\n /// the implementation of the `regex` crate.)\n #[default]\n Default,\n /// Dynamically select the right engine to use.\n ///\n /// This works by trying to use the default engine, and if the pattern does\n /// not compile, it switches over to the PCRE2 engine if it's available.\n Auto,\n /// Uses the PCRE2 regex engine if it's available.\n PCRE2,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":562,"symbol":"FieldContextSeparator","kind":"type","lang":"rust","doc":"The field context separator to use to between metadata for each contextual line. The default is `-`.","code":"pub(crate) struct FieldContextSeparator(BString);"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":565,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> FieldContextSeparator {\n FieldContextSeparator(BString::from(\"-\"))\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":573,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new separator from the given argument value provided by the user. Unescaping it automatically handled.","code":"pub(crate) fn new(os: &OsStr) -> anyhow::Result {\n let Some(string) = os.to_str() else {\n anyhow::bail!(\n \"separator must be valid UTF-8 (use escape sequences \\\n to provide a separator that is not valid UTF-8)\"\n )\n };\n Ok(FieldContextSeparator(Vec::unescape_bytes(string).into()))\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":586,"symbol":"into_bytes","kind":"function","lang":"rust","doc":"Return the raw bytes of this separator. Note that this may return an empty `Vec`.","code":"pub(crate) fn into_bytes(self) -> Vec {\n self.0.into()\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":596,"symbol":"FieldMatchSeparator","kind":"type","lang":"rust","doc":"The field match separator to use to between metadata for each matching line. The default is `:`.","code":"pub(crate) struct FieldMatchSeparator(BString);"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":599,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> FieldMatchSeparator {\n FieldMatchSeparator(BString::from(\":\"))\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":607,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new separator from the given argument value provided by the user. Unescaping it automatically handled.","code":"pub(crate) fn new(os: &OsStr) -> anyhow::Result {\n let Some(string) = os.to_str() else {\n anyhow::bail!(\n \"separator must be valid UTF-8 (use escape sequences \\\n to provide a separator that is not valid UTF-8)\"\n )\n };\n Ok(FieldMatchSeparator(Vec::unescape_bytes(string).into()))\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":620,"symbol":"into_bytes","kind":"function","lang":"rust","doc":"Return the raw bytes of this separator. Note that this may return an empty `Vec`.","code":"pub(crate) fn into_bytes(self) -> Vec {\n self.0.into()\n }"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":628,"symbol":"LoggingMode","kind":"type","lang":"rust","doc":"The type of logging to do. `Debug` emits some details while `Trace` emits much more.","code":"pub(crate) enum LoggingMode {\n Debug,\n Trace,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":637,"symbol":"MmapMode","kind":"type","lang":"rust","doc":"Indicates when to use memory maps. The default is `Auto`.","code":"pub(crate) enum MmapMode {\n /// This instructs ripgrep to use heuristics for selecting when to and not\n /// to use memory maps for searching.\n #[default]\n Auto,\n /// This instructs ripgrep to always try memory maps when possible. (Memory\n /// maps are not possible to use in all circumstances, for example, for\n /// virtual files.)\n AlwaysTryMmap,\n /// Never use memory maps under any circumstances. This includes even\n /// when multi-line search is enabled where ripgrep will read the entire\n /// contents of a file on to the heap before searching it.\n Never,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":657,"symbol":"PatternSource","kind":"type","lang":"rust","doc":"Represents a source of patterns that ripgrep should search for. The reason to unify these is so that we can retain the order of `-f/--flag` and `-e/--regexp` flags relative to one another.","code":"pub(crate) enum PatternSource {\n /// Comes from the `-e/--regexp` flag.\n Regexp(String),\n /// Comes from the `-f/--file` flag.\n File(PathBuf),\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":666,"symbol":"SortMode","kind":"type","lang":"rust","doc":"The sort criteria, if present.","code":"pub(crate) struct SortMode {\n /// Whether to reverse the sort criteria (i.e., descending order).\n pub(crate) reverse: bool,\n /// The actual sorting criteria.\n pub(crate) kind: SortModeKind,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":675,"symbol":"SortModeKind","kind":"type","lang":"rust","doc":"The criteria to use for sorting.","code":"pub(crate) enum SortModeKind {\n /// Sort by path.\n Path,\n /// Sort by last modified time.\n LastModified,\n /// Sort by last accessed time.\n LastAccessed,\n /// Sort by creation time.\n Created,\n}"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":689,"symbol":"supported","kind":"function","lang":"rust","doc":"Checks whether the selected sort mode is supported. If it isn't, an error (hopefully explaining why) is returned.","code":"pub(crate) fn supported(&self) -> anyhow::Result<()> {\n match self.kind {\n SortModeKind::Path => Ok(()),\n SortModeKind::LastModified => {\n let md = std::env::current_exe()\n .and_then(|p| p.metadata())\n .and_then(|md| md.modified());\n let Err(err) = md else { return Ok(()) };\n anyhow::bail!(\n \"sorting by last modified isn't supported: {err}\"\n );\n }\n SortModeKind::LastAccessed => {\n let md = std::env::current_exe()\n .and_then(|p| p.metadata())\n .and_then(|md| md.accessed());\n let Err(err) = md else { return Ok(()) };\n anyhow::bail!(\n \"sorting by last accessed isn't supported: {err}\"\n );\n }\n SortModeKind::Created => {\n let md = std::env::current_exe()\n .and_then(|p| p.metadata())\n .and_then(|md| md.created());\n let Err(err) = md else { return Ok(()) };\n anyhow::bail!(\n \"sorting by cr"} {"repo":"ripgrep","file":"crates/core/flags/lowargs.rs","line":726,"symbol":"TypeChange","kind":"type","lang":"rust","doc":"A single instance of either a change or a selection of one ripgrep's file types.","code":"pub(crate) enum TypeChange {\n /// Clear the given type from ripgrep.\n Clear { name: String },\n /// Add the given type definition (name and glob) to ripgrep.\n Add { def: String },\n /// Select the given type for filtering.\n Select { name: String },\n /// Select the given type for filtering but negate it.\n Negate { name: String },\n}"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":74,"symbol":"Flag","kind":"type","lang":"rust","doc":"`--no-encoding` negation flag for reverting back to \"automatic\" encoding detection. All three of `-E`, `--encoding` and `--no-encoding` are provided by a single implementation of this trait. ripgrep only supports flags that are switches or flags that accept a single value. Flags that accept multiple values are an unsupported aberration.","code":"trait Flag: Debug + Send + Sync + UnwindSafe + RefUnwindSafe + 'static {\n /// Returns true if this flag is a switch. When a flag is a switch, the\n /// CLI parser will not look for a value after the flag is seen.\n fn is_switch(&self) -> bool;\n\n /// A short single byte name for this flag. This returns `None` by default,\n /// which signifies that the flag has no short name.\n ///\n /// The byte returned must be an ASCII codepoint that is a `.` or is\n /// alpha-numeric.\n fn name_short(&self) -> Option {\n None\n }\n\n /// Returns the long name of this flag. All flags must have a \"long\" name.\n ///\n /// The long name must be at least 2 bytes, and all of its bytes must be\n /// ASCII codepoints that are either `-` or alpha-numeric.\n fn name_long(&self) -> &'static str;\n\n /// Returns a list of aliases for this flag.\n ///\n /// The aliases must follow the same rules as `Flag::name_long`.\n ///\n /// By default, an empty slice is returned.\n fn aliases(&self) -> &'static [&'static str] {\n &[]\n }\n\n /// Returns a negated name for this flag. The negation of a flag is\n /// intended to have the opposite meaning of a fl"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":77,"symbol":"is_switch","kind":"function","lang":"rust","doc":"Returns true if this flag is a switch. When a flag is a switch, the CLI parser will not look for a value after the flag is seen.","code":"fn is_switch(&self) -> bool;"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":84,"symbol":"name_short","kind":"function","lang":"rust","doc":"A short single byte name for this flag. This returns `None` by default, which signifies that the flag has no short name. The byte returned must be an ASCII codepoint that is a `.` or is alpha-numeric.","code":"fn name_short(&self) -> Option {\n None\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":92,"symbol":"name_long","kind":"function","lang":"rust","doc":"Returns the long name of this flag. All flags must have a \"long\" name. The long name must be at least 2 bytes, and all of its bytes must be ASCII codepoints that are either `-` or alpha-numeric.","code":"fn name_long(&self) -> &'static str;"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":99,"symbol":"aliases","kind":"function","lang":"rust","doc":"Returns a list of aliases for this flag. The aliases must follow the same rules as `Flag::name_long`. By default, an empty slice is returned.","code":"fn aliases(&self) -> &'static [&'static str] {\n &[]\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":114,"symbol":"name_negated","kind":"function","lang":"rust","doc":"output or man page. Instead, they are automatically mentioned at the end of the documentation section of the flag they negated. The aliases must follow the same rules as `Flag::name_long`. By default, a flag has no negation and this returns `None`.","code":"fn name_negated(&self) -> Option<&'static str> {\n None\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":127,"symbol":"doc_variable","kind":"function","lang":"rust","doc":"For example, the `--max-count` flag has its variable name set to `NUM`. The convention is to capitalize variable names. By default this returns `None`.","code":"fn doc_variable(&self) -> Option<&'static str> {\n None\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":135,"symbol":"doc_category","kind":"function","lang":"rust","doc":"Returns the category of this flag. Every flag must have a single category. Categories are used to organize flags in the generated documentation.","code":"fn doc_category(&self) -> Category;"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":142,"symbol":"doc_short","kind":"function","lang":"rust","doc":"A (very) short documentation string describing what this flag does. This may sacrifice \"proper English\" in order to be as terse as possible. Generally, we try to ensure that `rg -h` doesn't have any lines that exceed 79 columns.","code":"fn doc_short(&self) -> &'static str;"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":146,"symbol":"doc_long","kind":"function","lang":"rust","doc":"A (possibly very) longer documentation string describing in full detail what this flag does. This should be in mandoc/mdoc format.","code":"fn doc_long(&self) -> &'static str;"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":152,"symbol":"doc_choices","kind":"function","lang":"rust","doc":"If this is a non-switch flag that accepts a small set of specific values, then this should list them. This returns an empty slice by default.","code":"fn doc_choices(&self) -> &'static [&'static str] {\n &[]\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":156,"symbol":"completion_type","kind":"function","lang":"rust","code":"fn completion_type(&self) -> CompletionType {\n CompletionType::Other\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":180,"symbol":"update","kind":"function","lang":"rust","doc":"ensures that \"doing something\" occurs a minimal number of times. For example, by avoiding trying to find the hostname here, we can do it once later no matter how many times `--hostname-bin` is provided. Implementations should not include the flag name in the error message returned. The flag name is included automatically by the parser.","code":"fn update(\n &self,\n value: FlagValue,\n args: &mut crate::flags::lowargs::LowArgs,\n ) -> anyhow::Result<()>;"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":192,"symbol":"Category","kind":"type","lang":"rust","doc":"The category that a flag belongs to. Categories are used to organize flags into \"logical\" groups in the generated documentation.","code":"enum Category {\n /// Flags related to how ripgrep reads its input. Its \"input\" generally\n /// consists of the patterns it is trying to match and the haystacks it is\n /// trying to search.\n Input,\n /// Flags related to the operation of the search itself. For example,\n /// whether case insensitive matching is enabled.\n Search,\n /// Flags related to how ripgrep filters haystacks. For example, whether\n /// to respect gitignore files or not.\n Filter,\n /// Flags related to how ripgrep shows its search results. For example,\n /// whether to show line numbers or not.\n Output,\n /// Flags related to changing ripgrep's output at a more fundamental level.\n /// For example, flags like `--count` suppress printing of individual\n /// lines, and instead just print the total count of matches for each file\n /// searched.\n OutputModes,\n /// Flags related to indexing. This section includes flags both for\n /// searching an index and updating an index.\n Indexing,\n /// Flags related to logging behavior such as emitting non-fatal error\n /// messages or printing search statistics.\n Logging,\n /// Other behaviors not related to ripgrep'"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":228,"symbol":"as_str","kind":"function","lang":"rust","doc":"Returns a string representation of this category. This string is the name of the variable used in various templates for generated documentation. This name can be used for interpolation.","code":"fn as_str(&self) -> &'static str {\n match *self {\n Category::Input => \"input\",\n Category::Search => \"search\",\n Category::Filter => \"filter\",\n Category::Output => \"output\",\n Category::OutputModes => \"output-modes\",\n Category::Indexing => \"indexing\",\n Category::Logging => \"logging\",\n Category::OtherBehaviors => \"other-behaviors\",\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":244,"symbol":"CompletionType","kind":"type","lang":"rust","doc":"The kind of argument a flag accepts, to be used for shell completions.","code":"enum CompletionType {\n /// No special category. is_switch() and doc_choices() may apply.\n Other,\n /// A path to a file.\n Filename,\n /// A command in $PATH.\n Executable,\n /// The name of a file type, as used by e.g. --type.\n Filetype,\n /// The name of an encoding_rs encoding, as used by --encoding.\n Encoding,\n}"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":268,"symbol":"FlagValue","kind":"type","lang":"rust","doc":"Note that the CLI doesn't directly support negated switches. For example, you can'd do anything like `-n=false` or any of that nonsense. Instead, the CLI parser knows about which flag names are negations and which aren't (courtesy of the `Flag` trait). If a flag given is known as a negation, then a `FlagValue::Switch(false)` value is passed into `Flag::update`.","code":"enum FlagValue {\n /// A flag that is either on or off.\n Switch(bool),\n /// A flag that comes with an arbitrary user value.\n Value(OsString),\n}"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":284,"symbol":"unwrap_switch","kind":"function","lang":"rust","doc":"If this flag value is not a switch, then this panics. This is useful when writing the implementation of `Flag::update`. namely, callers usually know whether a switch or a value is expected. If a flag is something different, then it indicates a bug, and thus a panic is acceptable.","code":"fn unwrap_switch(self) -> bool {\n match self {\n FlagValue::Switch(yes) => yes,\n FlagValue::Value(_) => {\n unreachable!(\"got flag value but expected switch\")\n }\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/mod.rs","line":301,"symbol":"unwrap_value","kind":"function","lang":"rust","doc":"If this flag is a switch, then this panics. This is useful when writing the implementation of `Flag::update`. namely, callers usually know whether a switch or a value is expected. If a flag is something different, then it indicates a bug, and thus a panic is acceptable.","code":"fn unwrap_value(self) -> OsString {\n match self {\n FlagValue::Switch(_) => {\n unreachable!(\"got switch but expected flag value\")\n }\n FlagValue::Value(v) => v,\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":27,"symbol":"ParseResult","kind":"type","lang":"rust","doc":"user provides the `-h/--help` or `-V/--version` flags. This special variant exists to allow CLI parsing to short circuit as quickly as is reasonable. For example, it lets CLI parsing avoid reading ripgrep's configuration and converting low level arguments into a higher level representation.","code":"pub(crate) enum ParseResult {\n Special(SpecialMode),\n Ok(T),\n Err(anyhow::Error),\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":36,"symbol":"and_then","kind":"function","lang":"rust","doc":"If this result is `Ok`, then apply `then` to it. Otherwise, return this result unchanged.","code":"fn and_then(\n self,\n mut then: impl FnMut(T) -> ParseResult,\n ) -> ParseResult {\n match self {\n ParseResult::Special(mode) => ParseResult::Special(mode),\n ParseResult::Ok(t) => then(t),\n ParseResult::Err(err) => ParseResult::Err(err),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":49,"symbol":"parse","kind":"function","lang":"rust","doc":"Parse CLI arguments and convert then to their high level representation.","code":"pub(crate) fn parse() -> ParseResult {\n parse_low().and_then(|low| match HiArgs::from_low_args(low) {\n Ok(hi) => ParseResult::Ok(hi),\n Err(err) => ParseResult::Err(err),\n })\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":64,"symbol":"parse_low","kind":"function","lang":"rust","doc":"This takes configuration into account. That is, it will try to read `RIPGREP_CONFIG_PATH` and prepend any arguments found there to the arguments passed to this process. This will also set one-time global state flags, such as the log level and whether messages should be printed.","code":"fn parse_low() -> ParseResult {\n if let Err(err) = crate::logger::Logger::init() {\n let err = anyhow::anyhow!(\"failed to initialize logger: {err}\");\n return ParseResult::Err(err);\n }\n\n let parser = Parser::new();\n let mut low = LowArgs::default();\n if let Err(err) = parser.parse(std::env::args_os().skip(1), &mut low) {\n return ParseResult::Err(err);\n }\n // Even though we haven't parsed the config file yet (assuming it exists),\n // we can still use the arguments given on the CLI to setup ripgrep's\n // logging preferences. Even if the config file changes them in some way,\n // it's really the best we can do. This way, for example, folks can pass\n // `--trace` and see any messages logged during config file parsing.\n set_log_levels(&low);\n // Before we try to take configuration into account, we can bail early\n // if a special mode was enabled. This is basically only for version and\n // help output which shouldn't be impacted by extra configuration.\n if let Some(special) = low.special.take() {\n return ParseResult::Special(special);\n }\n // If the end user says no config, then respect it.\n if low."} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":116,"symbol":"set_log_levels","kind":"function","lang":"rust","doc":"Sets global state flags that control logging based on low-level arguments.","code":"fn set_log_levels(low: &LowArgs) {\n crate::messages::set_messages(!low.no_messages);\n crate::messages::set_ignore_messages(!low.no_ignore_messages);\n match low.logging {\n Some(LoggingMode::Trace) => {\n log::set_max_level(log::LevelFilter::Trace)\n }\n Some(LoggingMode::Debug) => {\n log::set_max_level(log::LevelFilter::Debug)\n }\n None => log::set_max_level(log::LevelFilter::Warn),\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":139,"symbol":"parse_low_raw","kind":"function","lang":"rust","doc":"This is exposed for testing that the correct low-level arguments are parsed from a CLI. It just runs the parser once over the CLI arguments. It doesn't setup logging or read from a config file. This assumes the iterator given does *not* begin with the binary name.","code":"pub(crate) fn parse_low_raw(\n rawargs: impl IntoIterator>,\n) -> anyhow::Result {\n let mut args = LowArgs::default();\n Parser::new().parse(rawargs, &mut args)?;\n Ok(args)\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":148,"symbol":"lookup","kind":"function","lang":"rust","doc":"Return the metadata for the flag of the given name.","code":"pub(super) fn lookup(name: &str) -> Option<&'static dyn Flag> {\n // N.B. Creating a new parser might look expensive, but it only builds\n // the lookup trie exactly once. That is, we get a `&'static Parser` from\n // `Parser::new()`.\n match Parser::new().find_long(name) {\n FlagLookup::Match(&FlagInfo { flag, .. }) => Some(flag),\n _ => None,\n }\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":161,"symbol":"Parser","kind":"type","lang":"rust","doc":"A parser for turning a sequence of command line arguments into a more strictly typed set of arguments.","code":"struct Parser {\n /// A single map that contains all possible flag names. This includes\n /// short and long names, aliases and negations. This maps those names to\n /// indices into `info`.\n map: FlagMap,\n /// A map from IDs returned by the `map` to the corresponding flag\n /// information.\n info: Vec,\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":176,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new parser. This always creates the same parser and only does it once. Callers may call this repeatedly, and the parser will only be built once.","code":"fn new() -> &'static Parser {\n use std::sync::OnceLock;\n\n // Since a parser's state is immutable and completely determined by\n // FLAGS, and since FLAGS is a constant, we can initialize it exactly\n // once.\n static P: OnceLock = OnceLock::new();\n P.get_or_init(|| {\n let mut infos = vec![];\n for &flag in FLAGS.iter() {\n infos.push(FlagInfo {\n flag,\n name: Ok(flag.name_long()),\n kind: FlagInfoKind::Standard,\n });\n for alias in flag.aliases() {\n infos.push(FlagInfo {\n flag,\n name: Ok(alias),\n kind: FlagInfoKind::Alias,\n });\n }\n if let Some(byte) = flag.name_short() {\n infos.push(FlagInfo {\n flag,\n name: Err(byte),\n kind: FlagInfoKind::Standard,\n });\n }\n if let Some(name) = flag.name_negated() {\n infos.push(FlagInfo {\n "} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":221,"symbol":"parse","kind":"function","lang":"rust","doc":"Parse the given CLI arguments into a low level representation. The iterator given should *not* start with the binary name.","code":"fn parse(&self, rawargs: I, args: &mut LowArgs) -> anyhow::Result<()>\n where\n I: IntoIterator,\n O: Into,\n {\n let mut p = lexopt::Parser::from_args(rawargs);\n while let Some(arg) = p.next().context(\"invalid CLI arguments\")? {\n let lookup = match arg {\n lexopt::Arg::Value(value) => {\n args.positional.push(value);\n continue;\n }\n lexopt::Arg::Short(ch) if ch == 'h' => {\n // Special case -h/--help since behavior is different\n // based on whether short or long flag is given.\n args.special = Some(SpecialMode::HelpShort);\n continue;\n }\n lexopt::Arg::Short(ch) if ch == 'V' => {\n // Special case -V/--version since behavior is different\n // based on whether short or long flag is given.\n args.special = Some(SpecialMode::VersionShort);\n continue;\n }\n lexopt::Arg::Short(ch) => self.find_short(ch),\n lexopt::Arg::Long(name)"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":293,"symbol":"find_short","kind":"function","lang":"rust","doc":"Look for a flag by its short name.","code":"fn find_short(&self, ch: char) -> FlagLookup<'_> {\n if !ch.is_ascii() {\n return FlagLookup::UnrecognizedShort(ch);\n }\n let byte = u8::try_from(ch).unwrap();\n let Some(index) = self.map.find(&[byte]) else {\n return FlagLookup::UnrecognizedShort(ch);\n };\n FlagLookup::Match(&self.info[index])\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":307,"symbol":"find_long","kind":"function","lang":"rust","doc":"Look for a flag by its long name. This also works for aliases and negated names.","code":"fn find_long(&self, name: &str) -> FlagLookup<'_> {\n let Some(index) = self.map.find(name.as_bytes()) else {\n return FlagLookup::UnrecognizedLong(name.to_string());\n };\n FlagLookup::Match(&self.info[index])\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":317,"symbol":"FlagLookup","kind":"type","lang":"rust","doc":"The result of looking up a flag name.","code":"enum FlagLookup<'a> {\n /// Lookup found a match and the metadata for the flag is attached.\n Match(&'a FlagInfo),\n /// The given short name is unrecognized.\n UnrecognizedShort(char),\n /// The given long name is unrecognized.\n UnrecognizedLong(String),\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":328,"symbol":"FlagInfo","kind":"type","lang":"rust","doc":"The info about a flag associated with a flag's ID in the flag map.","code":"struct FlagInfo {\n /// The flag object and its associated metadata.\n flag: &'static dyn Flag,\n /// The actual name that is stored in the Aho-Corasick automaton. When this\n /// is a byte, it corresponds to a short single character ASCII flag. The\n /// actual pattern that's in the Aho-Corasick automaton is just the single\n /// byte.\n name: Result<&'static str, u8>,\n /// The type of flag that is stored for the corresponding Aho-Corasick\n /// pattern.\n kind: FlagInfoKind,\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":343,"symbol":"FlagInfoKind","kind":"type","lang":"rust","doc":"The kind of flag that is being matched.","code":"enum FlagInfoKind {\n /// A standard flag, e.g., --passthru.\n Standard,\n /// A negation of a standard flag, e.g., --no-multiline.\n Negated,\n /// An alias for a standard flag, e.g., --passthrough.\n Alias,\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":353,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n match self.name {\n Ok(long) => write!(f, \"--{long}\"),\n Err(short) => write!(f, \"-{short}\", short = char::from(short)),\n }\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":366,"symbol":"FlagMap","kind":"type","lang":"rust","doc":"A map from flag names (short, long, negated and aliases) to their ID. Once an ID is known, it can be used to look up a flag's metadata in the parser's internal state.","code":"struct FlagMap {\n map: std::collections::HashMap, usize>,\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":374,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new map of flags for the given flag information. The index of each flag info corresponds to its ID.","code":"fn new(infos: &[FlagInfo]) -> FlagMap {\n let mut map = std::collections::HashMap::with_capacity(infos.len());\n for (i, info) in infos.iter().enumerate() {\n match info.name {\n Ok(name) => {\n assert_eq!(None, map.insert(name.as_bytes().to_vec(), i));\n }\n Err(byte) => {\n assert_eq!(None, map.insert(vec![byte], i));\n }\n }\n }\n FlagMap { map }\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":393,"symbol":"find","kind":"function","lang":"rust","doc":"Look for a match of `name` in the given Aho-Corasick automaton. This only returns a match if the one found has a length equivalent to the length of the name given.","code":"fn find(&self, name: &[u8]) -> Option {\n self.map.get(name).copied()\n }"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":404,"symbol":"suggest","kind":"function","lang":"rust","doc":"Possibly return a message suggesting flags similar in the name to the one given. The one given should be a flag given by the user (without the leading dashes) that was unrecognized. This attempts to find existing flags that are similar to the one given.","code":"fn suggest(unrecognized: &str) -> Option {\n let similars = find_similar_names(unrecognized);\n if similars.is_empty() {\n return None;\n }\n let list = similars\n .into_iter()\n .map(|name| format!(\"--{name}\"))\n .collect::>()\n .join(\", \");\n Some(format!(\"similar flags that are available: {list}\"))\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":418,"symbol":"find_similar_names","kind":"function","lang":"rust","doc":"Return a sequence of names similar to the unrecognized name given.","code":"fn find_similar_names(unrecognized: &str) -> Vec<&'static str> {\n // The jaccard similarity threshold at which we consider two flag names\n // similar enough that it's worth suggesting it to the end user.\n //\n // This value was determined by some ad hoc experimentation. It might need\n // further tweaking.\n const THRESHOLD: f64 = 0.4;\n\n let mut similar = vec![];\n let bow_given = ngrams(unrecognized);\n for &flag in FLAGS.iter() {\n let name = flag.name_long();\n let bow = ngrams(name);\n if jaccard_index(&bow_given, &bow) >= THRESHOLD {\n similar.push(name);\n }\n if let Some(name) = flag.name_negated() {\n let bow = ngrams(name);\n if jaccard_index(&bow_given, &bow) >= THRESHOLD {\n similar.push(name);\n }\n }\n for name in flag.aliases() {\n let bow = ngrams(name);\n if jaccard_index(&bow_given, &bow) >= THRESHOLD {\n similar.push(name);\n }\n }\n }\n similar\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":454,"symbol":"jaccard_index","kind":"function","lang":"rust","doc":"Returns the jaccard index (a measure of similarity) between sets of ngrams.","code":"fn jaccard_index(ngrams1: &BagOfWords<'_>, ngrams2: &BagOfWords<'_>) -> f64 {\n let union = u32::try_from(ngrams1.union(ngrams2).count())\n .expect(\"fewer than u32::MAX flags\");\n let intersection = u32::try_from(ngrams1.intersection(ngrams2).count())\n .expect(\"fewer than u32::MAX flags\");\n f64::from(intersection) / f64::from(union)\n}"} {"repo":"ripgrep","file":"crates/core/flags/parse.rs","line":466,"symbol":"ngrams","kind":"function","lang":"rust","doc":"Returns all 3-grams in the slice given. If the slice doesn't contain a 3-gram, then one is artificially created by padding it out with a character that will never appear in a flag name.","code":"fn ngrams(flag_name: &str) -> BagOfWords<'_> {\n // We only allow ASCII flag names, so we can just use bytes.\n let slice = flag_name.as_bytes();\n let seq: Vec> = match slice.len() {\n 0 => vec![Cow::Owned(b\"!!!\".to_vec())],\n 1 => vec![Cow::Owned(vec![slice[0], b'!', b'!'])],\n 2 => vec![Cow::Owned(vec![slice[0], slice[1], b'!'])],\n _ => slice.windows(3).map(Cow::Borrowed).collect(),\n };\n BTreeSet::from_iter(seq)\n}"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":16,"symbol":"HaystackBuilder","kind":"type","lang":"rust","doc":"A builder for constructing things to search over.","code":"pub(crate) struct HaystackBuilder {\n strip_dot_prefix: bool,\n}"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":22,"symbol":"new","kind":"function","lang":"rust","doc":"Return a new haystack builder with a default configuration.","code":"pub(crate) fn new() -> HaystackBuilder {\n HaystackBuilder { strip_dot_prefix: false }\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":31,"symbol":"build_from_result","kind":"function","lang":"rust","doc":"Create a new haystack from a possibly missing directory entry. If the directory entry isn't present, then the corresponding error is logged if messages have been configured. Otherwise, if the directory entry is deemed searchable, then it is returned as a haystack.","code":"pub(crate) fn build_from_result(\n &self,\n result: Result,\n ) -> Option {\n match result {\n Ok(dent) => self.build(dent),\n Err(err) => {\n err_message!(\"{err}\");\n None\n }\n }\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":49,"symbol":"build","kind":"function","lang":"rust","doc":"Create a new haystack using this builder's configuration. If a directory entry could not be created or should otherwise not be searched, then this returns `None` after emitting any relevant log messages.","code":"fn build(&self, dent: ignore::DirEntry) -> Option {\n let hay = Haystack { dent, strip_dot_prefix: self.strip_dot_prefix };\n if let Some(err) = hay.dent.error() {\n ignore_message!(\"{err}\");\n }\n // If this entry was explicitly provided by an end user, then we always\n // want to search it.\n if hay.is_explicit() {\n return Some(hay);\n }\n // At this point, we only want to search something if it's explicitly a\n // file. This omits symlinks. (If ripgrep was configured to follow\n // symlinks, then they have already been followed by the directory\n // traversal.)\n if hay.is_file() {\n return Some(hay);\n }\n // We got nothing. Emit a debug message, but only if this isn't a\n // directory. Otherwise, emitting messages for directories is just\n // noisy.\n if !hay.is_dir() {\n log::debug!(\n \"ignoring {}: failed to pass haystack filter: \\\n file type: {:?}, metadata: {:?}\",\n hay.dent.path().display(),\n hay.dent.file_type(),\n hay.dent.metadata()\n );"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":85,"symbol":"strip_dot_prefix","kind":"function","lang":"rust","doc":"When enabled, if the haystack's file path starts with `./` then it is stripped. This is useful when implicitly searching the current working directory.","code":"pub(crate) fn strip_dot_prefix(\n &mut self,\n yes: bool,\n ) -> &mut HaystackBuilder {\n self.strip_dot_prefix = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":98,"symbol":"Haystack","kind":"type","lang":"rust","doc":"A haystack is a thing we want to search. Generally, a haystack is either a file or stdin.","code":"pub(crate) struct Haystack {\n dent: ignore::DirEntry,\n strip_dot_prefix: bool,\n}"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":108,"symbol":"path","kind":"function","lang":"rust","doc":"Return the file path corresponding to this haystack. If this haystack corresponds to stdin, then a special `` path is returned instead.","code":"pub(crate) fn path(&self) -> &Path {\n if self.strip_dot_prefix && self.dent.path().starts_with(\"./\") {\n self.dent.path().strip_prefix(\"./\").unwrap()\n } else {\n self.dent.path()\n }\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":117,"symbol":"is_stdin","kind":"function","lang":"rust","doc":"Returns true if and only if this entry corresponds to stdin.","code":"pub(crate) fn is_stdin(&self) -> bool {\n self.dent.is_stdin()\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":131,"symbol":"is_explicit","kind":"function","lang":"rust","doc":"argument. e.g., in `rg foo some-file ./some-dir/`, `some-file` is an explicit haystack, but, e.g., `./some-dir/some-other-file` is not. However, note that ripgrep does not see through shell globbing. e.g., in `rg foo ./some-dir/*`, `./some-dir/some-other-file` will be treated as an explicit haystack.","code":"pub(crate) fn is_explicit(&self) -> bool {\n // stdin is obvious. When an entry has a depth of 0, that means it\n // was explicitly provided to our directory iterator, which means it\n // was in turn explicitly provided by the end user. The !is_dir check\n // means that we want to search files even if their symlinks, again,\n // because they were explicitly provided. (And we never want to try\n // to search a directory.)\n self.is_stdin() || (self.dent.depth() == 0 && !self.is_dir())\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":143,"symbol":"is_dir","kind":"function","lang":"rust","doc":"Returns true if and only if this haystack points to a directory after following symbolic links.","code":"fn is_dir(&self) -> bool {\n let ft = match self.dent.file_type() {\n None => return false,\n Some(ft) => ft,\n };\n if ft.is_dir() {\n return true;\n }\n // If this is a symlink, then we want to follow it to determine\n // whether it's a directory or not.\n self.dent.path_is_symlink() && self.dent.path().is_dir()\n }"} {"repo":"ripgrep","file":"crates/core/haystack.rs","line":157,"symbol":"is_file","kind":"function","lang":"rust","doc":"Returns true if and only if this haystack points to a file.","code":"fn is_file(&self) -> bool {\n self.dent.file_type().map_or(false, |ft| ft.is_file())\n }"} {"repo":"ripgrep","file":"crates/core/index/disabled.rs","line":3,"symbol":"write","kind":"function","lang":"rust","code":"pub(crate) fn write(_args: &HiArgs) -> anyhow::Result<()> {\n anyhow::bail!(\"indexing not enabled in this build of ripgrep\")\n}"} {"repo":"ripgrep","file":"crates/core/index/disabled.rs","line":7,"symbol":"read","kind":"function","lang":"rust","code":"pub(crate) fn read(_args: &HiArgs, _mode: SearchMode) -> anyhow::Result {\n anyhow::bail!(\"indexing not enabled in this build of ripgrep\")\n}"} {"repo":"ripgrep","file":"crates/core/index/enabled.rs","line":3,"symbol":"write","kind":"function","lang":"rust","code":"pub(crate) fn write(args: &HiArgs) -> anyhow::Result<()> {\n let _index = args.index_write()?;\n Ok(())\n}"} {"repo":"ripgrep","file":"crates/core/index/enabled.rs","line":8,"symbol":"read","kind":"function","lang":"rust","code":"pub(crate) fn read(args: &HiArgs, mode: SearchMode) -> anyhow::Result {\n let _index = args.index_read()?;\n // Do an exhaustive search for now.\n if args.threads() == 1 {\n crate::search(args, mode)\n } else {\n crate::search_parallel(args, mode)\n }\n}"} {"repo":"ripgrep","file":"crates/core/logger.rs","line":16,"symbol":"Logger","kind":"type","lang":"rust","doc":"The simplest possible logger that logs to stderr. This logger does no filtering. Instead, it relies on the `log` crates filtering via its global max_level setting.","code":"pub(crate) struct Logger(());"} {"repo":"ripgrep","file":"crates/core/logger.rs","line":25,"symbol":"init","kind":"function","lang":"rust","doc":"Create a new logger that logs to stderr and initialize it as the global logger. If there was a problem setting the logger, then an error is returned.","code":"pub(crate) fn init() -> Result<(), log::SetLoggerError> {\n log::set_logger(LOGGER)\n }"} {"repo":"ripgrep","file":"crates/core/logger.rs","line":31,"symbol":"enabled","kind":"function","lang":"rust","code":"fn enabled(&self, _: &log::Metadata<'_>) -> bool {\n // We set the log level via log::set_max_level, so we don't need to\n // implement filtering here.\n true\n }"} {"repo":"ripgrep","file":"crates/core/logger.rs","line":37,"symbol":"log","kind":"function","lang":"rust","code":"fn log(&self, record: &log::Record<'_>) {\n match (record.file(), record.line()) {\n (Some(file), Some(line)) => {\n eprintln_locked!(\n \"{}|{}|{}:{}: {}\",\n record.level(),\n record.target(),\n file,\n line,\n record.args()\n );\n }\n (Some(file), None) => {\n eprintln_locked!(\n \"{}|{}|{}: {}\",\n record.level(),\n record.target(),\n file,\n record.args()\n );\n }\n _ => {\n eprintln_locked!(\n \"{}|{}: {}\",\n record.level(),\n record.target(),\n record.args()\n );\n }\n }\n }"} {"repo":"ripgrep","file":"crates/core/logger.rs","line":69,"symbol":"flush","kind":"function","lang":"rust","code":"fn flush(&self) {\n // We use eprintln_locked! which is flushed on every call.\n }"} {"repo":"ripgrep","file":"crates/core/main.rs","line":44,"symbol":"main","kind":"function","lang":"rust","doc":"Then, as it was, then again it will be.","code":"fn main() -> ExitCode {\n match run(flags::parse()) {\n Ok(code) => code,\n Err(err) => {\n // Look for a broken pipe error. In this case, we generally want\n // to exit \"gracefully\" with a success exit code. This matches\n // existing Unix convention. We need to handle this explicitly\n // since the Rust runtime doesn't ask for PIPE signals, and thus\n // we get an I/O error instead. Traditional C Unix applications\n // quit by getting a PIPE signal that they don't handle, and thus\n // the unhandled signal causes the process to unceremoniously\n // terminate.\n for cause in err.chain() {\n if let Some(ioerr) = cause.downcast_ref::() {\n if ioerr.kind() == std::io::ErrorKind::BrokenPipe {\n return ExitCode::from(0);\n }\n }\n }\n eprintln_locked!(\"{:#}\", err);\n ExitCode::from(2)\n }\n }\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":78,"symbol":"run","kind":"function","lang":"rust","doc":"result should be the result of parsing CLI arguments in a low level representation, and then followed by an attempt to convert them into a higher level representation. The higher level representation has some nicer abstractions, for example, instead of representing the `-g/--glob` flag as a `Vec` (as in the low level representation), the globs are converted into a single matcher.","code":"fn run(result: crate::flags::ParseResult) -> anyhow::Result {\n use crate::flags::{Mode, ParseResult};\n\n let args = match result {\n ParseResult::Err(err) => return Err(err),\n ParseResult::Special(mode) => return special(mode),\n ParseResult::Ok(args) => args,\n };\n let matched = match args.mode() {\n Mode::Search(_) if !args.matches_possible() => false,\n Mode::Search(mode) if args.index() > 0 => index::read(&args, mode)?,\n Mode::Search(mode) if args.threads() == 1 => search(&args, mode)?,\n Mode::Search(mode) => search_parallel(&args, mode)?,\n Mode::Index(_) => {\n index::write(&args)?;\n return Ok(ExitCode::from(0));\n }\n Mode::Files if args.threads() == 1 => files(&args)?,\n Mode::Files => files_parallel(&args)?,\n Mode::Types => return types(&args),\n Mode::Generate(mode) => return generate(mode),\n };\n Ok(if matched && (args.quiet() || !messages::errored()) {\n ExitCode::from(0)\n } else if messages::errored() {\n ExitCode::from(2)\n } else {\n ExitCode::from(1)\n })\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":113,"symbol":"search","kind":"function","lang":"rust","doc":"The top-level entry point for single-threaded search. This recursively steps through the file list (current directory by default) and searches each file sequentially.","code":"fn search(args: &HiArgs, mode: SearchMode) -> anyhow::Result {\n let started_at = std::time::Instant::now();\n let haystack_builder = args.haystack_builder();\n let unsorted = args\n .walk_builder()?\n .build()\n .filter_map(|result| haystack_builder.build_from_result(result));\n let haystacks = args.sort(unsorted);\n\n let mut matched = false;\n let mut searched = false;\n let mut stats = args.stats();\n let mut searcher = args.search_worker(\n args.matcher()?,\n args.searcher()?,\n args.printer(mode, args.stdout()),\n )?;\n for haystack in haystacks {\n searched = true;\n let search_result = match searcher.search(&haystack) {\n Ok(search_result) => search_result,\n // A broken pipe means graceful termination.\n Err(err) if err.kind() == std::io::ErrorKind::BrokenPipe => break,\n Err(err) => {\n err_message!(\"{}: {}\", haystack.path().display(), err);\n continue;\n }\n };\n matched = matched || search_result.has_match();\n if let Some(ref mut stats) = stats {\n *stats += search_result.stats().unwrap();\n "} {"repo":"ripgrep","file":"crates/core/main.rs","line":166,"symbol":"search_parallel","kind":"function","lang":"rust","doc":"The parallelism is itself achieved by the recursive directory traversal. All we need to do is feed it a worker for performing a search on each file. Requesting a sorted output from ripgrep (such as with `--sort path`) will automatically disable parallelism and hence sorting is not handled here.","code":"fn search_parallel(args: &HiArgs, mode: SearchMode) -> anyhow::Result {\n use std::sync::atomic::{AtomicBool, Ordering};\n\n let started_at = std::time::Instant::now();\n let haystack_builder = args.haystack_builder();\n let bufwtr = args.buffer_writer();\n let stats = args.stats().map(std::sync::Mutex::new);\n let matched = AtomicBool::new(false);\n let searched = AtomicBool::new(false);\n\n let mut searcher = args.search_worker(\n args.matcher()?,\n args.searcher()?,\n args.printer(mode, bufwtr.buffer()),\n )?;\n args.walk_builder()?.build_parallel().run(|| {\n let bufwtr = &bufwtr;\n let stats = &stats;\n let matched = &matched;\n let searched = &searched;\n let haystack_builder = &haystack_builder;\n let mut searcher = searcher.clone();\n\n Box::new(move |result| {\n let haystack = match haystack_builder.build_from_result(result) {\n Some(haystack) => haystack,\n None => return WalkState::Continue,\n };\n searched.store(true, Ordering::SeqCst);\n searcher.printer().get_mut().clear();\n let search_result = match searcher"} {"repo":"ripgrep","file":"crates/core/main.rs","line":241,"symbol":"files","kind":"function","lang":"rust","doc":"The top-level entry point for file listing without searching. This recursively steps through the file list (current directory by default) and prints each path sequentially using a single thread.","code":"fn files(args: &HiArgs) -> anyhow::Result {\n let haystack_builder = args.haystack_builder();\n let unsorted = args\n .walk_builder()?\n .build()\n .filter_map(|result| haystack_builder.build_from_result(result));\n let haystacks = args.sort(unsorted);\n\n let mut matched = false;\n let mut path_printer = args.path_printer_builder().build(args.stdout());\n for haystack in haystacks {\n matched = true;\n if args.quit_after_match() {\n break;\n }\n if let Err(err) = path_printer.write(haystack.path()) {\n // A broken pipe means graceful termination.\n if err.kind() == std::io::ErrorKind::BrokenPipe {\n break;\n }\n // Otherwise, we have some other error that's preventing us from\n // writing to stdout, so we should bubble it up.\n return Err(err.into());\n }\n }\n Ok(matched)\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":277,"symbol":"files_parallel","kind":"function","lang":"rust","doc":"This recursively steps through the file list (current directory by default) and prints each path sequentially using multiple threads. Requesting a sorted output from ripgrep (such as with `--sort path`) will automatically disable parallelism and hence sorting is not handled here.","code":"fn files_parallel(args: &HiArgs) -> anyhow::Result {\n use std::{\n sync::{\n atomic::{AtomicBool, Ordering},\n mpsc,\n },\n thread,\n };\n\n let haystack_builder = args.haystack_builder();\n let mut path_printer = args.path_printer_builder().build(args.stdout());\n let matched = AtomicBool::new(false);\n let (tx, rx) = mpsc::channel::();\n\n // We spawn a single printing thread to make sure we don't tear writes.\n // We use a channel here under the presumption that it's probably faster\n // than using a mutex in the worker threads below, but this has never been\n // seriously litigated.\n let print_thread = thread::spawn(move || -> std::io::Result<()> {\n for haystack in rx.iter() {\n path_printer.write(haystack.path())?;\n }\n Ok(())\n });\n args.walk_builder()?.build_parallel().run(|| {\n let haystack_builder = &haystack_builder;\n let matched = &matched;\n let tx = tx.clone();\n\n Box::new(move |result| {\n let haystack = match haystack_builder.build_from_result(result) {\n Some(haystack) => haystack,\n "} {"repo":"ripgrep","file":"crates/core/main.rs","line":335,"symbol":"types","kind":"function","lang":"rust","doc":"The top-level entry point for `--type-list`.","code":"fn types(args: &HiArgs) -> anyhow::Result {\n let mut count = 0;\n let mut stdout = args.stdout();\n for def in args.types().definitions() {\n count += 1;\n stdout.write_all(def.name().as_bytes())?;\n stdout.write_all(b\": \")?;\n\n let mut first = true;\n for glob in def.globs() {\n if !first {\n stdout.write_all(b\", \")?;\n }\n stdout.write_all(glob.as_bytes())?;\n first = false;\n }\n stdout.write_all(b\"\\n\")?;\n }\n Ok(ExitCode::from(if count == 0 { 1 } else { 0 }))\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":361,"symbol":"generate","kind":"function","lang":"rust","doc":"Implements ripgrep's \"generate\" modes. These modes correspond to generating some kind of ancillary data related to ripgrep. At present, this includes ripgrep's man page (in roff format) and supported shell completions.","code":"fn generate(mode: crate::flags::GenerateMode) -> anyhow::Result {\n use crate::flags::GenerateMode;\n\n let output = match mode {\n GenerateMode::Man => flags::generate_man_page(),\n GenerateMode::CompleteBash => flags::generate_complete_bash(),\n GenerateMode::CompleteZsh => flags::generate_complete_zsh(),\n GenerateMode::CompleteFish => flags::generate_complete_fish(),\n GenerateMode::CompletePowerShell => {\n flags::generate_complete_powershell()\n }\n };\n writeln!(std::io::stdout(), \"{}\", output.trim_end())?;\n Ok(ExitCode::from(0))\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":389,"symbol":"special","kind":"function","lang":"rust","doc":"(within reason) that would prevent ripgrep from emitting help output. For example, part of the initialization logic that is skipped (among other things) is accessing the current working directory. If that fails, ripgrep emits an error. We don't want to emit an error if it fails and the user requested version or help information.","code":"fn special(mode: crate::flags::SpecialMode) -> anyhow::Result {\n use crate::flags::SpecialMode;\n\n let mut exit = ExitCode::from(0);\n let output = match mode {\n SpecialMode::HelpShort => flags::generate_help_short(),\n SpecialMode::HelpLong => flags::generate_help_long(),\n SpecialMode::VersionShort => flags::generate_version_short(),\n SpecialMode::VersionLong => flags::generate_version_long(),\n // --pcre2-version is a little special because it emits an error\n // exit code if this build of ripgrep doesn't support PCRE2.\n SpecialMode::VersionPCRE2 => {\n let (output, available) = flags::generate_version_pcre2();\n if !available {\n exit = ExitCode::from(1);\n }\n output\n }\n };\n writeln!(std::io::stdout(), \"{}\", output.trim_end())?;\n Ok(exit)\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":420,"symbol":"eprint_nothing_searched","kind":"function","lang":"rust","doc":"This can happen if an applicable ignore file has one or more rules that are too broad and cause ripgrep to ignore everything. We only show this error message when the user does *not* provide an explicit path to search. This is because the message can otherwise be noisy, e.g., when it is intended that there is nothing to search.","code":"fn eprint_nothing_searched() {\n err_message!(\n \"No files were searched, which means ripgrep probably \\\n applied a filter you didn't expect.\\n\\\n Running with --debug will show why files are being skipped.\"\n );\n}"} {"repo":"ripgrep","file":"crates/core/main.rs","line":440,"symbol":"print_stats","kind":"function","lang":"rust","doc":"If an error occurs while writing, then writing stops and the error is returned. Note that callers should probably ignore this error, since whether stats fail to print or not generally shouldn't cause ripgrep to enter into an \"error\" state. And usually the only way for this to fail is if writing to stdout itself fails.","code":"fn print_stats(\n mode: SearchMode,\n stats: &grep::printer::Stats,\n started: std::time::Instant,\n mut wtr: W,\n) -> std::io::Result<()> {\n let elapsed = std::time::Instant::now().duration_since(started);\n if matches!(mode, SearchMode::JSON) {\n // We specifically match the format laid out by the JSON printer in\n // the grep-printer crate. We simply \"extend\" it with the 'summary'\n // message type.\n serde_json::to_writer(\n &mut wtr,\n &serde_json::json!({\n \"type\": \"summary\",\n \"data\": {\n \"stats\": stats,\n \"elapsed_total\": {\n \"secs\": elapsed.as_secs(),\n \"nanos\": elapsed.subsec_nanos(),\n \"human\": format!(\"{:0.6}s\", elapsed.as_secs_f64()),\n },\n }\n }),\n )?;\n write!(wtr, \"\\n\")\n } else {\n write!(\n wtr,\n \"\n{matches} matches\n{lines} matched lines\n{searches_with_match} files contained matches\n{searches} files searched\n{bytes_printed} bytes printed\n{bytes_searched} bytes searched\n{search_time:0.6} s"} {"repo":"ripgrep","file":"crates/core/messages.rs","line":101,"symbol":"messages","kind":"function","lang":"rust","doc":"Returns true if and only if messages should be shown.","code":"pub(crate) fn messages() -> bool {\n MESSAGES.load(Ordering::Relaxed)\n}"} {"repo":"ripgrep","file":"crates/core/messages.rs","line":108,"symbol":"set_messages","kind":"function","lang":"rust","doc":"Set whether messages should be shown or not. By default, they are not shown.","code":"pub(crate) fn set_messages(yes: bool) {\n MESSAGES.store(yes, Ordering::Relaxed)\n}"} {"repo":"ripgrep","file":"crates/core/messages.rs","line":113,"symbol":"ignore_messages","kind":"function","lang":"rust","doc":"Returns true if and only if \"ignore\" related messages should be shown.","code":"pub(crate) fn ignore_messages() -> bool {\n IGNORE_MESSAGES.load(Ordering::Relaxed)\n}"} {"repo":"ripgrep","file":"crates/core/messages.rs","line":124,"symbol":"set_ignore_messages","kind":"function","lang":"rust","doc":"By default, they are not shown. Note that this is overridden if `messages` is disabled. Namely, if `messages` is disabled, then \"ignore\" messages are never shown, regardless of this setting.","code":"pub(crate) fn set_ignore_messages(yes: bool) {\n IGNORE_MESSAGES.store(yes, Ordering::Relaxed)\n}"} {"repo":"ripgrep","file":"crates/core/messages.rs","line":129,"symbol":"errored","kind":"function","lang":"rust","doc":"Returns true if and only if ripgrep came across a non-fatal error.","code":"pub(crate) fn errored() -> bool {\n ERRORED.load(Ordering::Relaxed)\n}"} {"repo":"ripgrep","file":"crates/core/messages.rs","line":137,"symbol":"set_errored","kind":"function","lang":"rust","doc":"Indicate that ripgrep has come across a non-fatal error. Callers should not use this directly. Instead, it is called automatically via the `err_message` macro.","code":"pub(crate) fn set_errored() {\n ERRORED.store(true, Ordering::Relaxed);\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":19,"symbol":"Config","kind":"type","lang":"rust","doc":"The configuration for the search worker. Among a few other things, the configuration primarily controls the way we show search results to users at a very high level.","code":"struct Config {\n preprocessor: Option,\n preprocessor_globs: ignore::overrides::Override,\n search_zip: bool,\n binary_implicit: grep::searcher::BinaryDetection,\n binary_explicit: grep::searcher::BinaryDetection,\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":28,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n preprocessor: None,\n preprocessor_globs: ignore::overrides::Override::empty(),\n search_zip: false,\n binary_implicit: grep::searcher::BinaryDetection::none(),\n binary_explicit: grep::searcher::BinaryDetection::none(),\n }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":41,"symbol":"SearchWorkerBuilder","kind":"type","lang":"rust","doc":"A builder for configuring and constructing a search worker.","code":"pub(crate) struct SearchWorkerBuilder {\n config: Config,\n command_builder: grep::cli::CommandReaderBuilder,\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":47,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> SearchWorkerBuilder {\n SearchWorkerBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":54,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for configuring and constructing a search worker.","code":"pub(crate) fn new() -> SearchWorkerBuilder {\n let mut command_builder = grep::cli::CommandReaderBuilder::new();\n command_builder.async_stderr(true);\n\n SearchWorkerBuilder { config: Config::default(), command_builder }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":63,"symbol":"build","kind":"function","lang":"rust","doc":"Create a new search worker using the given searcher, matcher and printer.","code":"pub(crate) fn build(\n &self,\n matcher: PatternMatcher,\n searcher: grep::searcher::Searcher,\n printer: Printer,\n ) -> SearchWorker {\n let config = self.config.clone();\n let command_builder = self.command_builder.clone();\n let decomp_builder = config.search_zip.then(|| {\n let mut decomp_builder =\n grep::cli::DecompressionReaderBuilder::new();\n decomp_builder.async_stderr(true);\n decomp_builder\n });\n SearchWorker {\n config,\n command_builder,\n decomp_builder,\n matcher,\n searcher,\n printer,\n }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":92,"symbol":"preprocessor","kind":"function","lang":"rust","doc":"Set the path to a preprocessor command. When this is set, instead of searching files directly, the given command will be run with the file path as the first argument, and the output of that command will be searched instead.","code":"pub(crate) fn preprocessor(\n &mut self,\n cmd: Option,\n ) -> anyhow::Result<&mut SearchWorkerBuilder> {\n if let Some(ref prog) = cmd {\n let bin = grep::cli::resolve_binary(prog)?;\n self.config.preprocessor = Some(bin);\n } else {\n self.config.preprocessor = None;\n }\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":108,"symbol":"preprocessor_globs","kind":"function","lang":"rust","doc":"Set the globs for determining which files should be run through the preprocessor. By default, with no globs and a preprocessor specified, every file is run through the preprocessor.","code":"pub(crate) fn preprocessor_globs(\n &mut self,\n globs: ignore::overrides::Override,\n ) -> &mut SearchWorkerBuilder {\n self.config.preprocessor_globs = globs;\n self\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":123,"symbol":"search_zip","kind":"function","lang":"rust","doc":"When enabled, if a particular file path is recognized as a compressed file, then it is decompressed before searching. Note that if a preprocessor command is set, then it overrides this setting.","code":"pub(crate) fn search_zip(\n &mut self,\n yes: bool,\n ) -> &mut SearchWorkerBuilder {\n self.config.search_zip = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":139,"symbol":"binary_detection_implicit","kind":"function","lang":"rust","doc":"Generally, this binary detection may be `grep::searcher::BinaryDetection::quit` if we want to skip binary files completely. By default, no binary detection is performed.","code":"pub(crate) fn binary_detection_implicit(\n &mut self,\n detection: grep::searcher::BinaryDetection,\n ) -> &mut SearchWorkerBuilder {\n self.config.binary_implicit = detection;\n self\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":155,"symbol":"binary_detection_explicit","kind":"function","lang":"rust","doc":"Generally, this binary detection should NOT be `grep::searcher::BinaryDetection::quit`, since we never want to automatically filter files supplied by the end user. By default, no binary detection is performed.","code":"pub(crate) fn binary_detection_explicit(\n &mut self,\n detection: grep::searcher::BinaryDetection,\n ) -> &mut SearchWorkerBuilder {\n self.config.binary_explicit = detection;\n self\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":171,"symbol":"SearchResult","kind":"type","lang":"rust","doc":"The result of executing a search. Generally speaking, the \"result\" of a search is sent to a printer, which writes results to an underlying writer such as stdout or a file. However, every search also has some aggregate statistics or meta data that may be useful to higher level routines.","code":"pub(crate) struct SearchResult {\n has_match: bool,\n stats: Option,\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":178,"symbol":"has_match","kind":"function","lang":"rust","doc":"Whether the search found a match or not.","code":"pub(crate) fn has_match(&self) -> bool {\n self.has_match\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":186,"symbol":"stats","kind":"function","lang":"rust","doc":"Return aggregate search statistics for a single search, if available. It can be expensive to compute statistics, so these are only present if explicitly enabled in the printer provided by the caller.","code":"pub(crate) fn stats(&self) -> Option<&grep::printer::Stats> {\n self.stats.as_ref()\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":193,"symbol":"PatternMatcher","kind":"type","lang":"rust","doc":"The pattern matcher used by a search worker.","code":"pub(crate) enum PatternMatcher {\n RustRegex(grep::regex::RegexMatcher),\n #[cfg(feature = \"pcre2\")]\n PCRE2(grep::pcre2::RegexMatcher),\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":203,"symbol":"Printer","kind":"type","lang":"rust","doc":"The printer used by a search worker. The `W` type parameter refers to the type of the underlying writer.","code":"pub(crate) enum Printer {\n /// Use the standard printer, which supports the classic grep-like format.\n Standard(grep::printer::Standard),\n /// Use the summary printer, which supports aggregate displays of search\n /// results.\n Summary(grep::printer::Summary),\n /// A JSON printer, which emits results in the JSON Lines format.\n JSON(grep::printer::JSON),\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":215,"symbol":"get_mut","kind":"function","lang":"rust","doc":"Return a mutable reference to the underlying printer's writer.","code":"pub(crate) fn get_mut(&mut self) -> &mut W {\n match *self {\n Printer::Standard(ref mut p) => p.get_mut(),\n Printer::Summary(ref mut p) => p.get_mut(),\n Printer::JSON(ref mut p) => p.get_mut(),\n }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":230,"symbol":"SearchWorker","kind":"type","lang":"rust","doc":"A worker for executing searches. It is intended for a single worker to execute many searches, and is generally intended to be used from a single thread. When searching using multiple threads, it is better to create a new worker for each thread.","code":"pub(crate) struct SearchWorker {\n config: Config,\n command_builder: grep::cli::CommandReaderBuilder,\n /// This is `None` when `search_zip` is not enabled, since in this case it\n /// can never be used. We do this because building the reader can sometimes\n /// do non-trivial work (like resolving the paths of decompression binaries\n /// on Windows).\n decomp_builder: Option,\n matcher: PatternMatcher,\n searcher: grep::searcher::Searcher,\n printer: Printer,\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":245,"symbol":"search","kind":"function","lang":"rust","doc":"Execute a search over the given haystack.","code":"pub(crate) fn search(\n &mut self,\n haystack: &crate::haystack::Haystack,\n ) -> io::Result {\n let bin = if haystack.is_explicit() {\n self.config.binary_explicit.clone()\n } else {\n self.config.binary_implicit.clone()\n };\n let path = haystack.path();\n log::trace!(\"{}: binary detection: {:?}\", path.display(), bin);\n\n self.searcher.set_binary_detection(bin);\n if haystack.is_stdin() {\n self.search_reader(path, &mut io::stdin().lock())\n } else if self.should_preprocess(path) {\n self.search_preprocessor(path)\n } else if self.should_decompress(path) {\n self.search_decompress(path)\n } else {\n self.search_path(path)\n }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":270,"symbol":"printer","kind":"function","lang":"rust","doc":"Return a mutable reference to the underlying printer.","code":"pub(crate) fn printer(&mut self) -> &mut Printer {\n &mut self.printer\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":276,"symbol":"should_decompress","kind":"function","lang":"rust","doc":"Returns true if and only if the given file path should be decompressed before searching.","code":"fn should_decompress(&self, path: &Path) -> bool {\n self.decomp_builder.as_ref().is_some_and(|decomp_builder| {\n decomp_builder.get_matcher().has_command(path)\n })\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":284,"symbol":"should_preprocess","kind":"function","lang":"rust","doc":"Returns true if and only if the given file path should be run through the preprocessor.","code":"fn should_preprocess(&self, path: &Path) -> bool {\n if !self.config.preprocessor.is_some() {\n return false;\n }\n if self.config.preprocessor_globs.is_empty() {\n return true;\n }\n !self.config.preprocessor_globs.matched(path, false).is_ignore()\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":296,"symbol":"search_preprocessor","kind":"function","lang":"rust","doc":"Search the given file path by first asking the preprocessor for the data to search instead of opening the path directly.","code":"fn search_preprocessor(\n &mut self,\n path: &Path,\n ) -> io::Result {\n use std::{fs::File, process::Stdio};\n\n let bin = self.config.preprocessor.as_ref().unwrap();\n let mut cmd = std::process::Command::new(bin);\n cmd.arg(path).stdin(Stdio::from(File::open(path)?));\n\n let mut rdr = self.command_builder.build(&mut cmd).map_err(|err| {\n io::Error::new(\n io::ErrorKind::Other,\n format!(\n \"preprocessor command could not start: '{cmd:?}': {err}\",\n ),\n )\n })?;\n let result = self.search_reader(path, &mut rdr).map_err(|err| {\n io::Error::new(\n io::ErrorKind::Other,\n format!(\"preprocessor command failed: '{cmd:?}': {err}\"),\n )\n });\n let close_result = rdr.close();\n let search_result = result?;\n close_result?;\n Ok(search_result)\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":329,"symbol":"search_decompress","kind":"function","lang":"rust","doc":"Attempt to decompress the data at the given file path and search the result. If the given file path isn't recognized as a compressed file, then search it without doing any decompression.","code":"fn search_decompress(&mut self, path: &Path) -> io::Result {\n let Some(ref decomp_builder) = self.decomp_builder else {\n return self.search_path(path);\n };\n let mut rdr = decomp_builder.build(path)?;\n let result = self.search_reader(path, &mut rdr);\n let close_result = rdr.close();\n let search_result = result?;\n close_result?;\n Ok(search_result)\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":342,"symbol":"search_path","kind":"function","lang":"rust","doc":"Search the contents of the given file path.","code":"fn search_path(&mut self, path: &Path) -> io::Result {\n use self::PatternMatcher::*;\n\n let (searcher, printer) = (&mut self.searcher, &mut self.printer);\n match self.matcher {\n RustRegex(ref m) => search_path(m, searcher, printer, path),\n #[cfg(feature = \"pcre2\")]\n PCRE2(ref m) => search_path(m, searcher, printer, path),\n }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":362,"symbol":"search_reader","kind":"function","lang":"rust","doc":"a preprocessor is set or when decompression is enabled). In those cases, the file path is used for visual purposes only. Generally speaking, this method should only be used when there is no other choice. Searching via `search_path` provides more opportunities for optimizations (such as memory maps).","code":"fn search_reader(\n &mut self,\n path: &Path,\n rdr: &mut R,\n ) -> io::Result {\n use self::PatternMatcher::*;\n\n let (searcher, printer) = (&mut self.searcher, &mut self.printer);\n match self.matcher {\n RustRegex(ref m) => search_reader(m, searcher, printer, path, rdr),\n #[cfg(feature = \"pcre2\")]\n PCRE2(ref m) => search_reader(m, searcher, printer, path, rdr),\n }\n }"} {"repo":"ripgrep","file":"crates/core/search.rs","line":380,"symbol":"search_path","kind":"function","lang":"rust","doc":"Search the contents of the given file path using the given matcher, searcher and printer.","code":"fn search_path(\n matcher: M,\n searcher: &mut grep::searcher::Searcher,\n printer: &mut Printer,\n path: &Path,\n) -> io::Result {\n match *printer {\n Printer::Standard(ref mut p) => {\n let mut sink = p.sink_with_path(&matcher, path);\n searcher.search_path(&matcher, path, &mut sink)?;\n Ok(SearchResult {\n has_match: sink.has_match(),\n stats: sink.stats().cloned(),\n })\n }\n Printer::Summary(ref mut p) => {\n let mut sink = p.sink_with_path(&matcher, path);\n searcher.search_path(&matcher, path, &mut sink)?;\n Ok(SearchResult {\n has_match: sink.has_match(),\n stats: sink.stats().cloned(),\n })\n }\n Printer::JSON(ref mut p) => {\n let mut sink = p.sink_with_path(&matcher, path);\n searcher.search_path(&matcher, path, &mut sink)?;\n Ok(SearchResult {\n has_match: sink.has_match(),\n stats: Some(sink.stats().clone()),\n })\n }\n }\n}"} {"repo":"ripgrep","file":"crates/core/search.rs","line":416,"symbol":"search_reader","kind":"function","lang":"rust","doc":"Search the contents of the given reader using the given matcher, searcher and printer.","code":"fn search_reader(\n matcher: M,\n searcher: &mut grep::searcher::Searcher,\n printer: &mut Printer,\n path: &Path,\n mut rdr: R,\n) -> io::Result {\n match *printer {\n Printer::Standard(ref mut p) => {\n let mut sink = p.sink_with_path(&matcher, path);\n searcher.search_reader(&matcher, &mut rdr, &mut sink)?;\n Ok(SearchResult {\n has_match: sink.has_match(),\n stats: sink.stats().cloned(),\n })\n }\n Printer::Summary(ref mut p) => {\n let mut sink = p.sink_with_path(&matcher, path);\n searcher.search_reader(&matcher, &mut rdr, &mut sink)?;\n Ok(SearchResult {\n has_match: sink.has_match(),\n stats: sink.stats().cloned(),\n })\n }\n Printer::JSON(ref mut p) => {\n let mut sink = p.sink_with_path(&matcher, path);\n searcher.search_reader(&matcher, &mut rdr, &mut sink)?;\n Ok(SearchResult {\n has_match: sink.has_match(),\n stats: Some(sink.stats().clone()),\n })\n }\n }\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":20,"symbol":"new_glob","kind":"function","lang":"rust","code":"fn new_glob(pat: &str) -> glob::Pattern {\n glob::Pattern::new(pat).unwrap()\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":24,"symbol":"new_reglob","kind":"function","lang":"rust","code":"fn new_reglob(pat: &str) -> GlobMatcher {\n Glob::new(pat).unwrap().compile_matcher()\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":28,"symbol":"new_reglob_many","kind":"function","lang":"rust","code":"fn new_reglob_many(pats: &[&str]) -> GlobSet {\n let mut builder = GlobSetBuilder::new();\n for pat in pats {\n builder.add(Glob::new(pat).unwrap());\n }\n builder.build().unwrap()\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":37,"symbol":"ext_glob","kind":"function","lang":"rust","code":"fn ext_glob(b: &mut test::Bencher) {\n let pat = new_glob(EXT_PAT);\n b.iter(|| assert!(pat.matches(EXT)));\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":43,"symbol":"ext_regex","kind":"function","lang":"rust","code":"fn ext_regex(b: &mut test::Bencher) {\n let set = new_reglob(EXT_PAT);\n let cand = Candidate::new(EXT);\n b.iter(|| assert!(set.is_match_candidate(&cand)));\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":50,"symbol":"short_glob","kind":"function","lang":"rust","code":"fn short_glob(b: &mut test::Bencher) {\n let pat = new_glob(SHORT_PAT);\n b.iter(|| assert!(pat.matches(SHORT)));\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":56,"symbol":"short_regex","kind":"function","lang":"rust","code":"fn short_regex(b: &mut test::Bencher) {\n let set = new_reglob(SHORT_PAT);\n let cand = Candidate::new(SHORT);\n b.iter(|| assert!(set.is_match_candidate(&cand)));\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":63,"symbol":"long_glob","kind":"function","lang":"rust","code":"fn long_glob(b: &mut test::Bencher) {\n let pat = new_glob(LONG_PAT);\n b.iter(|| assert!(pat.matches(LONG)));\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":69,"symbol":"long_regex","kind":"function","lang":"rust","code":"fn long_regex(b: &mut test::Bencher) {\n let set = new_reglob(LONG_PAT);\n let cand = Candidate::new(LONG);\n b.iter(|| assert!(set.is_match_candidate(&cand)));\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":96,"symbol":"many_short_glob","kind":"function","lang":"rust","code":"fn many_short_glob(b: &mut test::Bencher) {\n let pats: Vec<_> = MANY_SHORT_GLOBS.iter().map(|&s| new_glob(s)).collect();\n b.iter(|| {\n let mut count = 0;\n for pat in &pats {\n if pat.matches(MANY_SHORT_SEARCH) {\n count += 1;\n }\n }\n assert_eq!(2, count);\n })\n}"} {"repo":"ripgrep","file":"crates/globset/benches/bench.rs","line":110,"symbol":"many_short_regex_set","kind":"function","lang":"rust","code":"fn many_short_regex_set(b: &mut test::Bencher) {\n let set = new_reglob_many(MANY_SHORT_GLOBS);\n b.iter(|| assert_eq!(2, set.matches(MANY_SHORT_SEARCH).iter().count()));\n}"} {"repo":"ripgrep","file":"crates/globset/src/fnv.rs","line":6,"symbol":"Hasher","kind":"type","lang":"rust","doc":"A hasher that implements the Fowler–Noll–Vo (FNV) hash.","code":"pub(crate) struct Hasher(u64);"} {"repo":"ripgrep","file":"crates/globset/src/fnv.rs","line":14,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Hasher {\n Hasher(Hasher::OFFSET_BASIS)\n }"} {"repo":"ripgrep","file":"crates/globset/src/fnv.rs","line":20,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(&self) -> u64 {\n self.0\n }"} {"repo":"ripgrep","file":"crates/globset/src/fnv.rs","line":24,"symbol":"write","kind":"function","lang":"rust","code":"fn write(&mut self, bytes: &[u8]) {\n for &byte in bytes.iter() {\n self.0 = self.0 ^ u64::from(byte);\n self.0 = self.0.wrapping_mul(Hasher::PRIME);\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":16,"symbol":"MatchStrategy","kind":"type","lang":"rust","doc":"This provides a way to more quickly determine whether a pattern matches a particular file path in a way that scales with a large number of patterns. For example, if many patterns are of the form `*.ext`, then it's possible to test whether any of those patterns matches by looking up a file path's extension in a hash table.","code":"pub(crate) enum MatchStrategy {\n /// A pattern matches if and only if the entire file path matches this\n /// literal string.\n Literal(String),\n /// A pattern matches if and only if the file path's basename matches this\n /// literal string.\n BasenameLiteral(String),\n /// A pattern matches if and only if the file path's extension matches this\n /// literal string.\n Extension(String),\n /// A pattern matches if and only if this prefix literal is a prefix of the\n /// candidate file path.\n Prefix(String),\n /// A pattern matches if and only if this prefix literal is a prefix of the\n /// candidate file path.\n ///\n /// An exception: if `component` is true, then `suffix` must appear at the\n /// beginning of a file path or immediately following a `/`.\n Suffix {\n /// The actual suffix.\n suffix: String,\n /// Whether this must start at the beginning of a path component.\n component: bool,\n },\n /// A pattern matches only if the given extension matches the file path's\n /// extension. Note that this is a necessary but NOT sufficient criterion.\n /// Namely, if the extension matches, then a full regex search i"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":51,"symbol":"new","kind":"function","lang":"rust","doc":"Returns a matching strategy for the given pattern.","code":"pub(crate) fn new(pat: &Glob) -> MatchStrategy {\n if let Some(lit) = pat.basename_literal() {\n MatchStrategy::BasenameLiteral(lit)\n } else if let Some(lit) = pat.literal() {\n MatchStrategy::Literal(lit)\n } else if let Some(ext) = pat.ext() {\n MatchStrategy::Extension(ext)\n } else if let Some(prefix) = pat.prefix() {\n MatchStrategy::Prefix(prefix)\n } else if let Some((suffix, component)) = pat.suffix() {\n MatchStrategy::Suffix { suffix, component }\n } else if let Some(ext) = pat.required_ext() {\n MatchStrategy::RequiredExtension(ext)\n } else {\n MatchStrategy::Regex\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":76,"symbol":"Glob","kind":"type","lang":"rust","doc":"Glob represents a successfully parsed shell glob pattern. It cannot be used directly to match file paths, but it can be converted to a regular expression string or a matcher.","code":"pub struct Glob {\n glob: String,\n re: String,\n opts: GlobOptions,\n tokens: Tokens,\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":84,"symbol":"as_ref","kind":"function","lang":"rust","code":"fn as_ref(&self) -> &Glob {\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":90,"symbol":"eq","kind":"function","lang":"rust","code":"fn eq(&self, other: &Glob) -> bool {\n self.glob == other.glob && self.opts == other.opts\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":96,"symbol":"hash","kind":"function","lang":"rust","code":"fn hash(&self, state: &mut H) {\n self.glob.hash(state);\n self.opts.hash(state);\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":103,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n if f.alternate() {\n f.debug_struct(\"Glob\")\n .field(\"glob\", &self.glob)\n .field(\"re\", &self.re)\n .field(\"opts\", &self.opts)\n .field(\"tokens\", &self.tokens)\n .finish()\n } else {\n f.debug_tuple(\"Glob\").field(&self.glob).finish()\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":118,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n self.glob.fmt(f)\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":126,"symbol":"from_str","kind":"function","lang":"rust","code":"fn from_str(glob: &str) -> Result {\n Self::new(glob)\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":133,"symbol":"GlobMatcher","kind":"type","lang":"rust","doc":"A matcher for a single pattern.","code":"pub struct GlobMatcher {\n /// The underlying pattern.\n pat: Glob,\n /// The pattern, as a compiled regex.\n re: Regex,\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":142,"symbol":"is_match","kind":"function","lang":"rust","doc":"Tests whether the given path matches this pattern or not.","code":"pub fn is_match>(&self, path: P) -> bool {\n self.is_match_candidate(&Candidate::new(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":147,"symbol":"is_match_candidate","kind":"function","lang":"rust","doc":"Tests whether the given path matches this pattern or not.","code":"pub fn is_match_candidate(&self, path: &Candidate<'_>) -> bool {\n self.re.is_match(&path.path)\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":152,"symbol":"glob","kind":"function","lang":"rust","doc":"Returns the `Glob` used to compile this matcher.","code":"pub fn glob(&self) -> &Glob {\n &self.pat\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":160,"symbol":"GlobStrategic","kind":"type","lang":"rust","doc":"A strategic matcher for a single pattern.","code":"struct GlobStrategic {\n /// The match strategy to use.\n strategy: MatchStrategy,\n /// The pattern, as a compiled regex.\n re: Regex,\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":170,"symbol":"is_match","kind":"function","lang":"rust","doc":"Tests whether the given path matches this pattern or not.","code":"fn is_match>(&self, path: P) -> bool {\n self.is_match_candidate(&Candidate::new(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":175,"symbol":"is_match_candidate","kind":"function","lang":"rust","doc":"Tests whether the given path matches this pattern or not.","code":"fn is_match_candidate(&self, candidate: &Candidate<'_>) -> bool {\n let byte_path = &*candidate.path;\n\n match self.strategy {\n MatchStrategy::Literal(ref lit) => lit.as_bytes() == byte_path,\n MatchStrategy::BasenameLiteral(ref lit) => {\n lit.as_bytes() == &*candidate.basename\n }\n MatchStrategy::Extension(ref ext) => {\n ext.as_bytes() == &*candidate.ext\n }\n MatchStrategy::Prefix(ref pre) => {\n starts_with(pre.as_bytes(), byte_path)\n }\n MatchStrategy::Suffix { ref suffix, component } => {\n if component && byte_path == &suffix.as_bytes()[1..] {\n return true;\n }\n ends_with(suffix.as_bytes(), byte_path)\n }\n MatchStrategy::RequiredExtension(ref ext) => {\n let ext = ext.as_bytes();\n &*candidate.ext == ext && self.re.is_match(byte_path)\n }\n MatchStrategy::Regex => self.re.is_match(byte_path),\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":211,"symbol":"GlobBuilder","kind":"type","lang":"rust","doc":"A builder for a pattern. This builder enables configuring the match semantics of a pattern. For example, one can make matching case insensitive. The lifetime `'a` refers to the lifetime of the pattern string.","code":"pub struct GlobBuilder<'a> {\n /// The glob pattern to compile.\n glob: &'a str,\n /// Options for the pattern.\n opts: GlobOptions,\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":220,"symbol":"GlobOptions","kind":"type","lang":"rust","code":"struct GlobOptions {\n /// Whether to match case insensitively.\n case_insensitive: bool,\n /// Whether to require a literal separator to match a separator in a file\n /// path. e.g., when enabled, `*` won't match `/`.\n literal_separator: bool,\n /// Whether or not to use `\\` to escape special characters.\n /// e.g., when enabled, `\\*` will match a literal `*`.\n backslash_escape: bool,\n /// Whether or not an empty case in an alternate will be removed.\n /// e.g., when enabled, `{,a}` will match \"\" and \"a\".\n empty_alternates: bool,\n /// Whether or not an unclosed character class is allowed. When an unclosed\n /// character class is found, the opening `[` is treated as a literal `[`.\n /// When this isn't enabled, an opening `[` without a corresponding `]` is\n /// treated as an error.\n allow_unclosed_class: bool,\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":240,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> GlobOptions {\n GlobOptions {\n case_insensitive: false,\n literal_separator: false,\n backslash_escape: !is_separator('\\\\'),\n empty_alternates: false,\n allow_unclosed_class: false,\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":253,"symbol":"Tokens","kind":"type","lang":"rust","code":"struct Tokens(Vec);"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":257,"symbol":"deref","kind":"function","lang":"rust","code":"fn deref(&self) -> &Vec {\n &self.0\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":263,"symbol":"deref_mut","kind":"function","lang":"rust","code":"fn deref_mut(&mut self) -> &mut Vec {\n &mut self.0\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":270,"symbol":"Token","kind":"type","lang":"rust","code":"enum Token {\n Literal(char),\n Any,\n ZeroOrMore,\n RecursivePrefix,\n RecursiveSuffix,\n RecursiveZeroOrMore,\n Class { negated: bool, ranges: Vec<(char, char)> },\n Alternates(Vec),\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":283,"symbol":"new","kind":"function","lang":"rust","doc":"Builds a new pattern with default options.","code":"pub fn new(glob: &str) -> Result {\n GlobBuilder::new(glob).build()\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":288,"symbol":"compile_matcher","kind":"function","lang":"rust","doc":"Returns a matcher for this pattern.","code":"pub fn compile_matcher(&self) -> GlobMatcher {\n let re =\n new_regex(&self.re).expect(\"regex compilation shouldn't fail\");\n GlobMatcher { pat: self.clone(), re }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":300,"symbol":"compile_strategic_matcher","kind":"function","lang":"rust","doc":"Returns a strategic matcher. This isn't exposed because it's not clear whether it's actually faster than just running a regex for a *single* pattern. If it is faster, then GlobMatcher should do it automatically.","code":"fn compile_strategic_matcher(&self) -> GlobStrategic {\n let strategy = MatchStrategy::new(self);\n let re =\n new_regex(&self.re).expect(\"regex compilation shouldn't fail\");\n GlobStrategic { strategy, re }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":308,"symbol":"glob","kind":"function","lang":"rust","doc":"Returns the original glob pattern used to build this pattern.","code":"pub fn glob(&self) -> &str {\n &self.glob\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":326,"symbol":"regex","kind":"function","lang":"rust","doc":"[`regex`](https://crates.io/regex) crate's [`Regex`](https://docs.rs/regex/*/regex/struct.Regex.html) API is not suitable for this since it matches on `&str`, but its [`bytes::Regex`](https://docs.rs/regex/*/regex/bytes/struct.Regex.html) API is suitable for this.","code":"pub fn regex(&self) -> &str {\n &self.re\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":334,"symbol":"literal","kind":"function","lang":"rust","doc":"Returns the pattern as a literal if and only if the pattern must match an entire path exactly. The basic format of these patterns is `{literal}`.","code":"fn literal(&self) -> Option {\n if self.opts.case_insensitive {\n return None;\n }\n let mut lit = String::new();\n for t in &*self.tokens {\n let Token::Literal(c) = *t else { return None };\n lit.push(c);\n }\n if lit.is_empty() { None } else { Some(lit) }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":353,"symbol":"ext","kind":"function","lang":"rust","doc":"if the file path has the extension returned. Note that this extension returned differs from the extension that std::path::Path::extension returns. Namely, this extension includes the '.'. Also, paths like `.rs` are considered to have an extension of `.rs`.","code":"fn ext(&self) -> Option {\n if self.opts.case_insensitive {\n return None;\n }\n let start = match *self.tokens.get(0)? {\n Token::RecursivePrefix => 1,\n _ => 0,\n };\n match *self.tokens.get(start)? {\n Token::ZeroOrMore => {\n // If there was no recursive prefix, then we only permit\n // `*` if `*` can match a `/`. For example, if `*` can't\n // match `/`, then `*.c` doesn't match `foo/bar.c`.\n if start == 0 && self.opts.literal_separator {\n return None;\n }\n }\n _ => return None,\n }\n match *self.tokens.get(start + 1)? {\n Token::Literal('.') => {}\n _ => return None,\n }\n let mut lit = \".\".to_string();\n for t in self.tokens[start + 2..].iter() {\n match *t {\n Token::Literal('.') | Token::Literal('/') => return None,\n Token::Literal(c) => lit.push(c),\n _ => return None,\n }\n }\n if lit.is_empty() { None } else { Some(lit) }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":390,"symbol":"required_ext","kind":"function","lang":"rust","doc":"This is like `ext`, but returns an extension even if it isn't sufficient to imply a match. Namely, if an extension is returned, then it is necessary but not sufficient for a match.","code":"fn required_ext(&self) -> Option {\n if self.opts.case_insensitive {\n return None;\n }\n // We don't care at all about the beginning of this pattern. All we\n // need to check for is if it ends with a literal of the form `.ext`.\n let mut ext: Vec = vec![]; // built in reverse\n for t in self.tokens.iter().rev() {\n match *t {\n Token::Literal('/') => return None,\n Token::Literal(c) => {\n ext.push(c);\n if c == '.' {\n break;\n }\n }\n _ => return None,\n }\n }\n if ext.last() != Some(&'.') {\n None\n } else {\n ext.reverse();\n Some(ext.into_iter().collect())\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":419,"symbol":"prefix","kind":"function","lang":"rust","doc":"Returns a literal prefix of this pattern if the entire pattern matches if the literal prefix matches.","code":"fn prefix(&self) -> Option {\n if self.opts.case_insensitive {\n return None;\n }\n let (end, need_sep) = match *self.tokens.last()? {\n Token::ZeroOrMore => {\n if self.opts.literal_separator {\n // If a trailing `*` can't match a `/`, then we can't\n // assume a match of the prefix corresponds to a match\n // of the overall pattern. e.g., `foo/*` with\n // `literal_separator` enabled matches `foo/bar` but not\n // `foo/bar/baz`, even though `foo/bar/baz` has a `foo/`\n // literal prefix.\n return None;\n }\n (self.tokens.len() - 1, false)\n }\n Token::RecursiveSuffix => (self.tokens.len() - 1, true),\n _ => (self.tokens.len(), false),\n };\n let mut lit = String::new();\n for t in &self.tokens[0..end] {\n let Token::Literal(c) = *t else { return None };\n lit.push(c);\n }\n if need_sep {\n lit.push('/');\n }\n if lit.is_empty() { None } else { Some(lit) }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":462,"symbol":"suffix","kind":"function","lang":"rust","doc":"`foo/bar` and `baz/foo/bar`, but not `foofoo/bar`. In this case, the suffix returned is `/foo/bar` (but should match the entire path `foo/bar`). When this returns true, the suffix literal is guaranteed to start with a `/`.","code":"fn suffix(&self) -> Option<(String, bool)> {\n if self.opts.case_insensitive {\n return None;\n }\n let mut lit = String::new();\n let (start, entire) = match *self.tokens.get(0)? {\n Token::RecursivePrefix => {\n // We only care if this follows a path component if the next\n // token is a literal.\n if let Some(&Token::Literal(_)) = self.tokens.get(1) {\n lit.push('/');\n (1, true)\n } else {\n (1, false)\n }\n }\n _ => (0, false),\n };\n let start = match *self.tokens.get(start)? {\n Token::ZeroOrMore => {\n // If literal_separator is enabled, then a `*` can't\n // necessarily match everything, so reporting a suffix match\n // as a match of the pattern would be a false positive.\n if self.opts.literal_separator {\n return None;\n }\n start + 1\n }\n _ => start,\n };\n for t in &self.tokens[start..] {\n let Token::Literal(c) = *t els"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":510,"symbol":"basename_tokens","kind":"function","lang":"rust","doc":"Note that this will return None if any match of the basename tokens doesn't correspond to a match of the entire pattern. For example, the glob `foo` only matches when a file path has a basename of `foo`, but doesn't *always* match when a file path has a basename of `foo`. e.g., `foo` doesn't match `abc/foo`.","code":"fn basename_tokens(&self) -> Option<&[Token]> {\n if self.opts.case_insensitive {\n return None;\n }\n let start = match *self.tokens.get(0)? {\n Token::RecursivePrefix => 1,\n _ => {\n // With nothing to gobble up the parent portion of a path,\n // we can't assume that matching on only the basename is\n // correct.\n return None;\n }\n };\n if self.tokens[start..].is_empty() {\n return None;\n }\n for t in self.tokens[start..].iter() {\n match *t {\n Token::Literal('/') => return None,\n Token::Literal(_) => {} // OK\n Token::Any | Token::ZeroOrMore => {\n if !self.opts.literal_separator {\n // In this case, `*` and `?` can match a path\n // separator, which means this could reach outside\n // the basename.\n return None;\n }\n }\n Token::RecursivePrefix\n | Token::RecursiveSuffix\n | Token::RecursiveZeroOrM"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":559,"symbol":"basename_literal","kind":"function","lang":"rust","doc":"Returns the pattern as a literal if and only if the pattern exclusively matches the basename of a file path *and* is a literal. The basic format of these patterns is `**/{literal}`, where `{literal}` does not contain a path separator.","code":"fn basename_literal(&self) -> Option {\n let tokens = self.basename_tokens()?;\n let mut lit = String::new();\n for t in tokens {\n let Token::Literal(c) = *t else { return None };\n lit.push(c);\n }\n Some(lit)\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":574,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for the pattern given. The pattern is not compiled until `build` is called.","code":"pub fn new(glob: &'a str) -> GlobBuilder<'a> {\n GlobBuilder { glob, opts: GlobOptions::default() }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":579,"symbol":"build","kind":"function","lang":"rust","doc":"Parses and builds the pattern.","code":"pub fn build(&self) -> Result {\n let mut p = Parser {\n glob: &self.glob,\n alternates_stack: Vec::new(),\n branches: vec![Tokens::default()],\n chars: self.glob.chars().peekable(),\n prev: None,\n cur: None,\n found_unclosed_class: false,\n opts: &self.opts,\n };\n p.parse()?;\n if p.branches.is_empty() {\n // OK because of how the the branches/alternate_stack are managed.\n // If we end up here, then there *must* be a bug in the parser\n // somewhere.\n unreachable!()\n } else if p.branches.len() > 1 {\n Err(Error {\n glob: Some(self.glob.to_string()),\n kind: ErrorKind::UnclosedAlternates,\n })\n } else {\n let tokens = p.branches.pop().unwrap();\n Ok(Glob {\n glob: self.glob.to_string(),\n re: tokens.to_regex_with(&self.opts),\n opts: self.opts,\n tokens,\n })\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":615,"symbol":"case_insensitive","kind":"function","lang":"rust","doc":"Toggle whether the pattern matches case insensitively or not. This is disabled by default.","code":"pub fn case_insensitive(&mut self, yes: bool) -> &mut GlobBuilder<'a> {\n self.opts.case_insensitive = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":623,"symbol":"literal_separator","kind":"function","lang":"rust","doc":"Toggle whether a literal `/` is required to match a path separator. By default this is false: `*` and `?` will match `/`.","code":"pub fn literal_separator(&mut self, yes: bool) -> &mut GlobBuilder<'a> {\n self.opts.literal_separator = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":636,"symbol":"backslash_escape","kind":"function","lang":"rust","doc":"prevent `\\` from being interpreted as a path separator on all platforms. This is enabled by default on platforms where `\\` is not a path separator and disabled by default on platforms where `\\` is a path separator.","code":"pub fn backslash_escape(&mut self, yes: bool) -> &mut GlobBuilder<'a> {\n self.opts.backslash_escape = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":647,"symbol":"empty_alternates","kind":"function","lang":"rust","doc":"Toggle whether an empty pattern in a list of alternates is accepted. For example, if this is set then the glob `foo{,.txt}` will match both `foo` and `foo.txt`. By default this is false.","code":"pub fn empty_alternates(&mut self, yes: bool) -> &mut GlobBuilder<'a> {\n self.opts.empty_alternates = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":663,"symbol":"allow_unclosed_class","kind":"function","lang":"rust","doc":"literal string `[abc` instead of returning an error. By default, this is false. Generally speaking, enabling this leads to worse failure modes since the glob parser becomes more permissive. You might want to enable this when compatibility (e.g., with POSIX glob implementations) is more important than good error messages.","code":"pub fn allow_unclosed_class(&mut self, yes: bool) -> &mut GlobBuilder<'a> {\n self.opts.allow_unclosed_class = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":673,"symbol":"to_regex_with","kind":"function","lang":"rust","doc":"Convert this pattern to a string that is guaranteed to be a valid regular expression and will represent the matching semantics of this glob pattern and the options given.","code":"fn to_regex_with(&self, options: &GlobOptions) -> String {\n let mut re = String::new();\n re.push_str(\"(?-u)\");\n if options.case_insensitive {\n re.push_str(\"(?i)\");\n }\n re.push('^');\n // Special case. If the entire glob is just `**`, then it should match\n // everything.\n if self.len() == 1 && self[0] == Token::RecursivePrefix {\n re.push_str(\".*\");\n re.push('$');\n return re;\n }\n self.tokens_to_regex(options, &self, &mut re);\n re.push('$');\n re\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":692,"symbol":"tokens_to_regex","kind":"function","lang":"rust","code":"fn tokens_to_regex(\n &self,\n options: &GlobOptions,\n tokens: &[Token],\n re: &mut String,\n ) {\n for tok in tokens.iter() {\n match *tok {\n Token::Literal(c) => {\n re.push_str(&char_to_escaped_literal(c));\n }\n Token::Any => {\n if options.literal_separator {\n re.push_str(\"[^/]\");\n } else {\n re.push_str(\".\");\n }\n }\n Token::ZeroOrMore => {\n if options.literal_separator {\n re.push_str(\"[^/]*\");\n } else {\n re.push_str(\".*\");\n }\n }\n Token::RecursivePrefix => {\n re.push_str(\"(?:/?|.*/)\");\n }\n Token::RecursiveSuffix => {\n re.push_str(\"/.*\");\n }\n Token::RecursiveZeroOrMore => {\n re.push_str(\"(?:/|/.*/)\");\n }\n Token::Class { negated, ref ranges } => {\n re.push"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":768,"symbol":"char_to_escaped_literal","kind":"function","lang":"rust","doc":"Convert a Unicode scalar value to an escaped string suitable for use as a literal in a non-Unicode regex.","code":"fn char_to_escaped_literal(c: char) -> String {\n let mut buf = [0; 4];\n let bytes = c.encode_utf8(&mut buf).as_bytes();\n bytes_to_escaped_literal(bytes)\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":776,"symbol":"bytes_to_escaped_literal","kind":"function","lang":"rust","doc":"Converts an arbitrary sequence of bytes to a UTF-8 string. All non-ASCII code units are converted to their escaped form.","code":"fn bytes_to_escaped_literal(bs: &[u8]) -> String {\n let mut s = String::with_capacity(bs.len());\n for &b in bs {\n if b <= 0x7F {\n regex_syntax::escape_into(\n char::from(b).encode_utf8(&mut [0; 4]),\n &mut s,\n );\n } else {\n write!(&mut s, \"\\\\x{:02x}\", b).unwrap();\n }\n }\n s\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":791,"symbol":"Parser","kind":"type","lang":"rust","code":"struct Parser<'a> {\n /// The glob to parse.\n glob: &'a str,\n /// Marks the index in `stack` where the alternation started.\n alternates_stack: Vec,\n /// The set of active alternation branches being parsed.\n /// Tokens are added to the end of the last one.\n branches: Vec,\n /// A character iterator over the glob pattern to parse.\n chars: std::iter::Peekable>,\n /// The previous character seen.\n prev: Option,\n /// The current character.\n cur: Option,\n /// Whether we failed to find a closing `]` for a character\n /// class. This can only be true when `GlobOptions::allow_unclosed_class`\n /// is enabled. When enabled, it is impossible to ever parse another\n /// character class with this glob. That's because classes cannot be\n /// nested *and* the only way this happens is when there is never a `]`.\n ///\n /// We track this state so that we don't end up spending quadratic time\n /// trying to parse something like `[[[[[[[[[[[[[[[[[[[[[[[...`.\n found_unclosed_class: bool,\n /// Glob options, which may influence parsing.\n opts: &'a GlobOptions,\n}"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":819,"symbol":"error","kind":"function","lang":"rust","code":"fn error(&self, kind: ErrorKind) -> Error {\n Error { glob: Some(self.glob.to_string()), kind }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":823,"symbol":"parse","kind":"function","lang":"rust","code":"fn parse(&mut self) -> Result<(), Error> {\n while let Some(c) = self.bump() {\n match c {\n '?' => self.push_token(Token::Any)?,\n '*' => self.parse_star()?,\n '[' if !self.found_unclosed_class => self.parse_class()?,\n '{' => self.push_alternate()?,\n '}' => self.pop_alternate()?,\n ',' => self.parse_comma()?,\n '\\\\' => self.parse_backslash()?,\n c => self.push_token(Token::Literal(c))?,\n }\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":839,"symbol":"push_alternate","kind":"function","lang":"rust","code":"fn push_alternate(&mut self) -> Result<(), Error> {\n self.alternates_stack.push(self.branches.len());\n self.branches.push(Tokens::default());\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":845,"symbol":"pop_alternate","kind":"function","lang":"rust","code":"fn pop_alternate(&mut self) -> Result<(), Error> {\n let Some(start) = self.alternates_stack.pop() else {\n return Err(self.error(ErrorKind::UnopenedAlternates));\n };\n assert!(start <= self.branches.len());\n let alts = Token::Alternates(self.branches.drain(start..).collect());\n self.push_token(alts)?;\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":855,"symbol":"push_token","kind":"function","lang":"rust","code":"fn push_token(&mut self, tok: Token) -> Result<(), Error> {\n if let Some(ref mut pat) = self.branches.last_mut() {\n return Ok(pat.push(tok));\n }\n Err(self.error(ErrorKind::UnopenedAlternates))\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":862,"symbol":"pop_token","kind":"function","lang":"rust","code":"fn pop_token(&mut self) -> Result {\n if let Some(ref mut pat) = self.branches.last_mut() {\n return Ok(pat.pop().unwrap());\n }\n Err(self.error(ErrorKind::UnopenedAlternates))\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":869,"symbol":"have_tokens","kind":"function","lang":"rust","code":"fn have_tokens(&self) -> Result {\n match self.branches.last() {\n None => Err(self.error(ErrorKind::UnopenedAlternates)),\n Some(ref pat) => Ok(!pat.is_empty()),\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":876,"symbol":"parse_comma","kind":"function","lang":"rust","code":"fn parse_comma(&mut self) -> Result<(), Error> {\n // If we aren't inside a group alternation, then don't\n // treat commas specially. Otherwise, we need to start\n // a new alternate branch.\n if self.alternates_stack.is_empty() {\n self.push_token(Token::Literal(','))\n } else {\n Ok(self.branches.push(Tokens::default()))\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":887,"symbol":"parse_backslash","kind":"function","lang":"rust","code":"fn parse_backslash(&mut self) -> Result<(), Error> {\n if self.opts.backslash_escape {\n match self.bump() {\n None => Err(self.error(ErrorKind::DanglingEscape)),\n Some(c) => self.push_token(Token::Literal(c)),\n }\n } else if is_separator('\\\\') {\n // Normalize all patterns to use / as a separator.\n self.push_token(Token::Literal('/'))\n } else {\n self.push_token(Token::Literal('\\\\'))\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":901,"symbol":"parse_star","kind":"function","lang":"rust","code":"fn parse_star(&mut self) -> Result<(), Error> {\n let prev = self.prev;\n if self.peek() != Some('*') {\n self.push_token(Token::ZeroOrMore)?;\n return Ok(());\n }\n assert!(self.bump() == Some('*'));\n if !self.have_tokens()? {\n if !self.peek().map_or(true, is_separator) {\n self.push_token(Token::ZeroOrMore)?;\n self.push_token(Token::ZeroOrMore)?;\n } else {\n self.push_token(Token::RecursivePrefix)?;\n assert!(self.bump().map_or(true, is_separator));\n }\n return Ok(());\n }\n\n if !prev.map(is_separator).unwrap_or(false) {\n if self.branches.len() <= 1\n || (prev != Some(',') && prev != Some('{'))\n {\n self.push_token(Token::ZeroOrMore)?;\n self.push_token(Token::ZeroOrMore)?;\n return Ok(());\n }\n }\n let is_suffix = match self.peek() {\n None => {\n assert!(self.bump().is_none());\n true\n }\n Some(',') | Some('}') if self.branches.len() >= 2 => true,\n S"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":962,"symbol":"parse_class","kind":"function","lang":"rust","code":"fn parse_class(&mut self) -> Result<(), Error> {\n // Save parser state for potential rollback to literal '[' parsing.\n let saved_chars = self.chars.clone();\n let saved_prev = self.prev;\n let saved_cur = self.cur;\n\n fn add_to_last_range(\n glob: &str,\n r: &mut (char, char),\n add: char,\n ) -> Result<(), Error> {\n r.1 = add;\n if r.1 < r.0 {\n Err(Error {\n glob: Some(glob.to_string()),\n kind: ErrorKind::InvalidRange(r.0, r.1),\n })\n } else {\n Ok(())\n }\n }\n let mut ranges = vec![];\n let negated = match self.chars.peek() {\n Some(&'!') | Some(&'^') => {\n let bump = self.bump();\n assert!(bump == Some('!') || bump == Some('^'));\n true\n }\n _ => false,\n };\n let mut first = true;\n let mut in_range = false;\n loop {\n let Some(c) = self.bump() else {\n return if self.opts.allow_unclosed_class == true {\n self.chars = saved_chars;\n "} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":968,"symbol":"add_to_last_range","kind":"function","lang":"rust","code":"fn add_to_last_range(\n glob: &str,\n r: &mut (char, char),\n add: char,\n ) -> Result<(), Error> {\n r.1 = add;\n if r.1 < r.0 {\n Err(Error {\n glob: Some(glob.to_string()),\n kind: ErrorKind::InvalidRange(r.0, r.1),\n })\n } else {\n Ok(())\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/glob.rs","line":1054,"symbol":"bump","kind":"function","lang":"rust","code":"fn bump(&mut self) -> Option {\n self.prev = self.cur;\n self.cur = self.chars.next();\n self.cur\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":157,"symbol":"Error","kind":"type","lang":"rust","doc":"Represents an error that can occur when parsing a glob pattern.","code":"pub struct Error {\n /// The original glob provided by the caller.\n glob: Option,\n /// The kind of error.\n kind: ErrorKind,\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":167,"symbol":"ErrorKind","kind":"type","lang":"rust","doc":"The kind of error that can occur when parsing a glob pattern.","code":"pub enum ErrorKind {\n /// **DEPRECATED**.\n ///\n /// This error used to occur for consistency with git's glob specification,\n /// but the specification now accepts all uses of `**`. When `**` does not\n /// appear adjacent to a path separator or at the beginning/end of a glob,\n /// it is now treated as two consecutive `*` patterns. As such, this error\n /// is no longer used.\n InvalidRecursive,\n /// Occurs when a character class (e.g., `[abc]`) is not closed.\n UnclosedClass,\n /// Occurs when a range in a character (e.g., `[a-z]`) is invalid. For\n /// example, if the range starts with a lexicographically larger character\n /// than it ends with.\n InvalidRange(char, char),\n /// Occurs when a `}` is found without a matching `{`.\n UnopenedAlternates,\n /// Occurs when a `{` is found without a matching `}`.\n UnclosedAlternates,\n /// **DEPRECATED**.\n ///\n /// This error used to occur when an alternating group was nested inside\n /// another alternating group, e.g., `{{a,b},{c,d}}`. However, this is now\n /// supported and as such this error cannot occur.\n NestedAlternates,\n /// Occurs when an unescaped '\\' is found at th"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":199,"symbol":"description","kind":"function","lang":"rust","code":"fn description(&self) -> &str {\n self.kind.description()\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":206,"symbol":"glob","kind":"function","lang":"rust","doc":"Return the glob that caused this error, if one exists.","code":"pub fn glob(&self) -> Option<&str> {\n self.glob.as_ref().map(|s| &**s)\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":211,"symbol":"kind","kind":"function","lang":"rust","doc":"Return the kind of this error.","code":"pub fn kind(&self) -> &ErrorKind {\n &self.kind\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":217,"symbol":"description","kind":"function","lang":"rust","code":"fn description(&self) -> &str {\n match *self {\n ErrorKind::InvalidRecursive => {\n \"invalid use of **; must be one path component\"\n }\n ErrorKind::UnclosedClass => {\n \"unclosed character class; missing ']'\"\n }\n ErrorKind::InvalidRange(_, _) => \"invalid character range\",\n ErrorKind::UnopenedAlternates => {\n \"unopened alternate group; missing '{' \\\n (maybe escape '}' with '[}]'?)\"\n }\n ErrorKind::UnclosedAlternates => {\n \"unclosed alternate group; missing '}' \\\n (maybe escape '{' with '[{]'?)\"\n }\n ErrorKind::NestedAlternates => {\n \"nested alternate groups are not allowed\"\n }\n ErrorKind::DanglingEscape => \"dangling '\\\\'\",\n ErrorKind::Regex(ref err) => err,\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":244,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self.glob {\n None => self.kind.fmt(f),\n Some(ref glob) => {\n write!(f, \"error parsing glob '{}': {}\", glob, self.kind)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":255,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match *self {\n ErrorKind::InvalidRecursive\n | ErrorKind::UnclosedClass\n | ErrorKind::UnopenedAlternates\n | ErrorKind::UnclosedAlternates\n | ErrorKind::NestedAlternates\n | ErrorKind::DanglingEscape\n | ErrorKind::Regex(_) => write!(f, \"{}\", self.description()),\n ErrorKind::InvalidRange(s, e) => {\n write!(f, \"invalid range; '{}' > '{}'\", s, e)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":271,"symbol":"new_regex","kind":"function","lang":"rust","code":"fn new_regex(pat: &str) -> Result {\n let syntax = regex_automata::util::syntax::Config::new()\n .utf8(false)\n .dot_matches_new_line(true);\n let config = Regex::config()\n .utf8_empty(false)\n .nfa_size_limit(Some(10 * (1 << 20)))\n .hybrid_cache_capacity(10 * (1 << 20));\n Regex::builder().syntax(syntax).configure(config).build(pat).map_err(\n |err| Error {\n glob: Some(pat.to_string()),\n kind: ErrorKind::Regex(err.to_string()),\n },\n )\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":287,"symbol":"new_regex_set","kind":"function","lang":"rust","code":"fn new_regex_set(pats: Vec) -> Result {\n let syntax = regex_automata::util::syntax::Config::new()\n .utf8(false)\n .dot_matches_new_line(true);\n let config = Regex::config()\n .match_kind(regex_automata::MatchKind::All)\n .utf8_empty(false)\n .nfa_size_limit(Some(10 * (1 << 20)))\n .hybrid_cache_capacity(10 * (1 << 20));\n Regex::builder()\n .syntax(syntax)\n .configure(config)\n .build_many(&pats)\n .map_err(|err| Error {\n glob: None,\n kind: ErrorKind::Regex(err.to_string()),\n })\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":309,"symbol":"GlobSet","kind":"type","lang":"rust","doc":"GlobSet represents a group of globs that can be matched together in a single pass.","code":"pub struct GlobSet {\n len: usize,\n strats: Vec,\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":319,"symbol":"builder","kind":"function","lang":"rust","doc":"Create a new [`GlobSetBuilder`]. A `GlobSetBuilder` can be used to add new patterns. Once all patterns have been added, `build` should be called to produce a `GlobSet`, which can then be used for matching.","code":"pub fn builder() -> GlobSetBuilder {\n GlobSetBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":325,"symbol":"empty","kind":"function","lang":"rust","doc":"Create an empty `GlobSet`. An empty set matches nothing.","code":"pub const fn empty() -> GlobSet {\n GlobSet { len: 0, strats: vec![] }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":331,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if this set is empty, and therefore matches nothing.","code":"pub fn is_empty(&self) -> bool {\n self.len == 0\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":337,"symbol":"len","kind":"function","lang":"rust","doc":"Returns the number of globs in this set.","code":"pub fn len(&self) -> usize {\n self.len\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":342,"symbol":"is_match","kind":"function","lang":"rust","doc":"Returns true if any glob in this set matches the path given.","code":"pub fn is_match>(&self, path: P) -> bool {\n self.is_match_candidate(&Candidate::new(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":350,"symbol":"is_match_candidate","kind":"function","lang":"rust","doc":"Returns true if any glob in this set matches the path given. This takes a Candidate as input, which can be used to amortize the cost of preparing a path for matching.","code":"pub fn is_match_candidate(&self, path: &Candidate<'_>) -> bool {\n if self.is_empty() {\n return false;\n }\n for strat in &self.strats {\n if strat.is_match(path) {\n return true;\n }\n }\n false\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":379,"symbol":"matches_all","kind":"function","lang":"rust","doc":"let set = builder.build().unwrap(); assert!(set.matches_all(\"src/foo.rs\")); assert!(!set.matches_all(\"src/bar.c\")); assert!(!set.matches_all(\"test.rs\")); ```","code":"pub fn matches_all>(&self, path: P) -> bool {\n self.matches_all_candidate(&Candidate::new(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":390,"symbol":"matches_all_candidate","kind":"function","lang":"rust","doc":"This takes a Candidate as input, which can be used to amortize the cost of preparing a path for matching. This will return true if the set of globs is empty, as in that case all `0` of the globs will match.","code":"pub fn matches_all_candidate(&self, path: &Candidate<'_>) -> bool {\n for strat in &self.strats {\n if !strat.matches_all(path) {\n return false;\n }\n }\n true\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":401,"symbol":"matches","kind":"function","lang":"rust","doc":"Returns the sequence number of every glob pattern that matches the given path.","code":"pub fn matches>(&self, path: P) -> Vec {\n self.matches_candidate(&Candidate::new(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":410,"symbol":"matches_candidate","kind":"function","lang":"rust","doc":"Returns the sequence number of every glob pattern that matches the given path. This takes a Candidate as input, which can be used to amortize the cost of preparing a path for matching.","code":"pub fn matches_candidate(&self, path: &Candidate<'_>) -> Vec {\n let mut into = vec![];\n if self.is_empty() {\n return into;\n }\n self.matches_candidate_into(path, &mut into);\n into\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":425,"symbol":"matches_into","kind":"function","lang":"rust","doc":"Adds the sequence number of every glob pattern that matches the given path to the vec given. `into` is cleared before matching begins, and contains the set of sequence numbers (in ascending order) after matching ends. If no globs were matched, then `into` will be empty.","code":"pub fn matches_into>(\n &self,\n path: P,\n into: &mut Vec,\n ) {\n self.matches_candidate_into(&Candidate::new(path.as_ref()), into);\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":442,"symbol":"matches_candidate_into","kind":"function","lang":"rust","doc":"`into` is cleared before matching begins, and contains the set of sequence numbers (in ascending order) after matching ends. If no globs were matched, then `into` will be empty. This takes a Candidate as input, which can be used to amortize the cost of preparing a path for matching.","code":"pub fn matches_candidate_into(\n &self,\n path: &Candidate<'_>,\n into: &mut Vec,\n ) {\n into.clear();\n if self.is_empty() {\n return;\n }\n for strat in &self.strats {\n strat.matches_into(path, into);\n }\n into.sort();\n into.dedup();\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":461,"symbol":"new","kind":"function","lang":"rust","doc":"Builds a new matcher from a collection of Glob patterns. Once a matcher is built, no new patterns can be added to it.","code":"pub fn new(globs: I) -> Result\n where\n I: IntoIterator,\n G: AsRef,\n {\n let mut it = globs.into_iter().peekable();\n if it.peek().is_none() {\n return Ok(GlobSet::empty());\n }\n\n let mut len = 0;\n let mut lits = LiteralStrategy::new();\n let mut base_lits = BasenameLiteralStrategy::new();\n let mut exts = ExtensionStrategy::new();\n let mut prefixes = MultiStrategyBuilder::new();\n let mut suffixes = MultiStrategyBuilder::new();\n let mut required_exts = RequiredExtensionStrategyBuilder::new();\n let mut regexes = MultiStrategyBuilder::new();\n for (i, p) in it.enumerate() {\n len += 1;\n\n let p = p.as_ref();\n match MatchStrategy::new(p) {\n MatchStrategy::Literal(lit) => {\n lits.add(i, lit);\n }\n MatchStrategy::BasenameLiteral(lit) => {\n base_lits.add(i, lit);\n }\n MatchStrategy::Extension(ext) => {\n exts.add(i, ext);\n }\n MatchStrategy::Prefix(prefix) => "} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":558,"symbol":"default","kind":"function","lang":"rust","doc":"Create a default empty GlobSet.","code":"fn default() -> Self {\n GlobSet::empty()\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":566,"symbol":"GlobSetBuilder","kind":"type","lang":"rust","doc":"GlobSetBuilder builds a group of patterns that can be used to simultaneously match a file path.","code":"pub struct GlobSetBuilder {\n pats: Vec,\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":574,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new `GlobSetBuilder`. A `GlobSetBuilder` can be used to add new patterns. Once all patterns have been added, `build` should be called to produce a [`GlobSet`], which can then be used for matching.","code":"pub fn new() -> GlobSetBuilder {\n GlobSetBuilder { pats: vec![] }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":581,"symbol":"build","kind":"function","lang":"rust","doc":"Builds a new matcher from all of the glob patterns added so far. Once a matcher is built, no new patterns can be added to it.","code":"pub fn build(&self) -> Result {\n GlobSet::new(self.pats.iter())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":586,"symbol":"add","kind":"function","lang":"rust","doc":"Add a new pattern to this set.","code":"pub fn add(&mut self, pat: Glob) -> &mut GlobSetBuilder {\n self.pats.push(pat);\n self\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":599,"symbol":"Candidate","kind":"type","lang":"rust","doc":"A candidate path for matching. All glob matching in this crate operates on `Candidate` values. Constructing candidates has a very small cost associated with it, so callers may find it beneficial to amortize that cost when matching a single path against multiple globs or sets of globs.","code":"pub struct Candidate<'a> {\n path: Cow<'a, [u8]>,\n basename: Cow<'a, [u8]>,\n ext: Cow<'a, [u8]>,\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":606,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n f.debug_struct(\"Candidate\")\n .field(\"path\", &self.path.as_bstr())\n .field(\"basename\", &self.basename.as_bstr())\n .field(\"ext\", &self.ext.as_bstr())\n .finish()\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":617,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new candidate for matching from the given path.","code":"pub fn new + ?Sized>(path: &'a P) -> Candidate<'a> {\n Self::from_cow(Vec::from_path_lossy(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":629,"symbol":"from_bytes","kind":"function","lang":"rust","doc":"Generally speaking, this routine expects the bytes to be _conventionally_ UTF-8. It is legal for the byte sequence to contain invalid UTF-8. However, if the bytes are in some other encoding that isn't ASCII compatible (for example, UTF-16), then the results of matching are unspecified.","code":"pub fn from_bytes + ?Sized>(path: &'a P) -> Candidate<'a> {\n Self::from_cow(Cow::Borrowed(path.as_ref()))\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":633,"symbol":"from_cow","kind":"function","lang":"rust","code":"fn from_cow(path: Cow<'a, [u8]>) -> Candidate<'a> {\n let path = normalize_path(path);\n let basename = file_name(&path).unwrap_or(Cow::Borrowed(B(\"\")));\n let ext = file_name_ext(&basename).unwrap_or(Cow::Borrowed(B(\"\")));\n Candidate { path, basename, ext }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":640,"symbol":"path_prefix","kind":"function","lang":"rust","code":"fn path_prefix(&self, max: usize) -> &[u8] {\n if self.path.len() <= max { &*self.path } else { &self.path[..max] }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":644,"symbol":"path_suffix","kind":"function","lang":"rust","code":"fn path_suffix(&self, max: usize) -> &[u8] {\n if self.path.len() <= max {\n &*self.path\n } else {\n &self.path[self.path.len() - max..]\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":654,"symbol":"GlobSetMatchStrategy","kind":"type","lang":"rust","code":"enum GlobSetMatchStrategy {\n Literal(LiteralStrategy),\n BasenameLiteral(BasenameLiteralStrategy),\n Extension(ExtensionStrategy),\n Prefix(PrefixStrategy),\n Suffix(SuffixStrategy),\n RequiredExtension(RequiredExtensionStrategy),\n Regex(RegexSetStrategy),\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":665,"symbol":"is_match","kind":"function","lang":"rust","code":"fn is_match(&self, candidate: &Candidate<'_>) -> bool {\n use self::GlobSetMatchStrategy::*;\n match *self {\n Literal(ref s) => s.is_match(candidate),\n BasenameLiteral(ref s) => s.is_match(candidate),\n Extension(ref s) => s.is_match(candidate),\n Prefix(ref s) => s.is_match(candidate),\n Suffix(ref s) => s.is_match(candidate),\n RequiredExtension(ref s) => s.is_match(candidate),\n Regex(ref s) => s.is_match(candidate),\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":678,"symbol":"matches_into","kind":"function","lang":"rust","code":"fn matches_into(\n &self,\n candidate: &Candidate<'_>,\n matches: &mut Vec,\n ) {\n use self::GlobSetMatchStrategy::*;\n match *self {\n Literal(ref s) => s.matches_into(candidate, matches),\n BasenameLiteral(ref s) => s.matches_into(candidate, matches),\n Extension(ref s) => s.matches_into(candidate, matches),\n Prefix(ref s) => s.matches_into(candidate, matches),\n Suffix(ref s) => s.matches_into(candidate, matches),\n RequiredExtension(ref s) => s.matches_into(candidate, matches),\n Regex(ref s) => s.matches_into(candidate, matches),\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":695,"symbol":"matches_all","kind":"function","lang":"rust","code":"fn matches_all(&self, candidate: &Candidate<'_>) -> bool {\n use self::GlobSetMatchStrategy::*;\n match *self {\n Literal(ref s) => s.matches_all(candidate),\n BasenameLiteral(ref s) => s.matches_all(candidate),\n Extension(ref s) => s.matches_all(candidate),\n Prefix(ref s) => s.matches_all(candidate),\n Suffix(ref s) => s.matches_all(candidate),\n RequiredExtension(ref s) => s.matches_all(candidate),\n Regex(ref s) => s.matches_all(candidate),\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":710,"symbol":"LiteralStrategy","kind":"type","lang":"rust","code":"struct LiteralStrategy(fnv::HashMap, Vec>);"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":713,"symbol":"new","kind":"function","lang":"rust","code":"fn new() -> LiteralStrategy {\n LiteralStrategy(fnv::HashMap::default())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":717,"symbol":"add","kind":"function","lang":"rust","code":"fn add(&mut self, global_index: usize, lit: String) {\n self.0.entry(lit.into_bytes()).or_insert(vec![]).push(global_index);\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":721,"symbol":"is_match","kind":"function","lang":"rust","code":"fn is_match(&self, candidate: &Candidate<'_>) -> bool {\n self.0.contains_key(candidate.path.as_bytes())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":725,"symbol":"matches_all","kind":"function","lang":"rust","code":"fn matches_all(&self, candidate: &Candidate<'_>) -> bool {\n self.0.len() == 1 && self.is_match(candidate)\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":730,"symbol":"matches_into","kind":"function","lang":"rust","code":"fn matches_into(\n &self,\n candidate: &Candidate<'_>,\n matches: &mut Vec,\n ) {\n if let Some(hits) = self.0.get(candidate.path.as_bytes()) {\n matches.extend(hits);\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":742,"symbol":"BasenameLiteralStrategy","kind":"type","lang":"rust","code":"struct BasenameLiteralStrategy(fnv::HashMap, Vec>);"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":745,"symbol":"new","kind":"function","lang":"rust","code":"fn new() -> BasenameLiteralStrategy {\n BasenameLiteralStrategy(fnv::HashMap::default())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":749,"symbol":"add","kind":"function","lang":"rust","code":"fn add(&mut self, global_index: usize, lit: String) {\n self.0.entry(lit.into_bytes()).or_insert(vec![]).push(global_index);\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":753,"symbol":"is_match","kind":"function","lang":"rust","code":"fn is_match(&self, candidate: &Candidate<'_>) -> bool {\n if candidate.basename.is_empty() {\n return false;\n }\n self.0.contains_key(candidate.basename.as_bytes())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":760,"symbol":"matches_all","kind":"function","lang":"rust","code":"fn matches_all(&self, candidate: &Candidate<'_>) -> bool {\n self.0.len() == 1 && self.is_match(candidate)\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":765,"symbol":"matches_into","kind":"function","lang":"rust","code":"fn matches_into(\n &self,\n candidate: &Candidate<'_>,\n matches: &mut Vec,\n ) {\n if candidate.basename.is_empty() {\n return;\n }\n if let Some(hits) = self.0.get(candidate.basename.as_bytes()) {\n matches.extend(hits);\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":780,"symbol":"ExtensionStrategy","kind":"type","lang":"rust","code":"struct ExtensionStrategy(fnv::HashMap, Vec>);"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":783,"symbol":"new","kind":"function","lang":"rust","code":"fn new() -> ExtensionStrategy {\n ExtensionStrategy(fnv::HashMap::default())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":787,"symbol":"add","kind":"function","lang":"rust","code":"fn add(&mut self, global_index: usize, ext: String) {\n self.0.entry(ext.into_bytes()).or_insert(vec![]).push(global_index);\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":791,"symbol":"is_match","kind":"function","lang":"rust","code":"fn is_match(&self, candidate: &Candidate<'_>) -> bool {\n if candidate.ext.is_empty() {\n return false;\n }\n self.0.contains_key(candidate.ext.as_bytes())\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":798,"symbol":"matches_all","kind":"function","lang":"rust","code":"fn matches_all(&self, candidate: &Candidate<'_>) -> bool {\n self.0.len() == 1 && self.is_match(candidate)\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":803,"symbol":"matches_into","kind":"function","lang":"rust","code":"fn matches_into(\n &self,\n candidate: &Candidate<'_>,\n matches: &mut Vec,\n ) {\n if candidate.ext.is_empty() {\n return;\n }\n if let Some(hits) = self.0.get(candidate.ext.as_bytes()) {\n matches.extend(hits);\n }\n }"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":818,"symbol":"PrefixStrategy","kind":"type","lang":"rust","code":"struct PrefixStrategy {\n matcher: AhoCorasick,\n map: Vec,\n longest: usize,\n}"} {"repo":"ripgrep","file":"crates/globset/src/lib.rs","line":825,"symbol":"is_match","kind":"function","lang":"rust","code":"fn is_match(&self, candidate: &Candidate<'_>) -> bool {\n let path = candidate.path_prefix(self.longest);\n for m in self.matcher.find_overlapping_iter(path) {\n if m.start() == 0 {\n return true;\n }\n }\n false\n }"} {"repo":"ripgrep","file":"crates/globset/src/pathutil.rs","line":9,"symbol":"file_name","kind":"function","lang":"rust","doc":"The final component of the path, if it is a normal file. If the path terminates in `..`, or consists solely of a root of prefix, file_name will return `None`.","code":"pub(crate) fn file_name<'a>(path: &Cow<'a, [u8]>) -> Option> {\n if path.is_empty() {\n return None;\n }\n let last_slash = path.rfind_byte(b'/').map(|i| i + 1).unwrap_or(0);\n let got = match *path {\n Cow::Borrowed(path) => Cow::Borrowed(&path[last_slash..]),\n Cow::Owned(ref path) => Cow::Owned(path[last_slash..].to_vec()),\n };\n if got == &b\"..\"[..] {\n return None;\n }\n Some(got)\n}"} {"repo":"ripgrep","file":"crates/globset/src/pathutil.rs","line":40,"symbol":"file_name_ext","kind":"function","lang":"rust","doc":"e.g., A file name of `.rs` has an extension `.rs`. N.B. This is done to make certain glob match optimizations easier. Namely, a pattern like `*.rs` is obviously trying to match files with a `rs` extension, but it also matches files like `.rs`, which doesn't have an extension according to std::path::Path::extension.","code":"pub(crate) fn file_name_ext<'a>(\n name: &Cow<'a, [u8]>,\n) -> Option> {\n if name.is_empty() {\n return None;\n }\n let last_dot_at = match name.rfind_byte(b'.') {\n None => return None,\n Some(i) => i,\n };\n Some(match *name {\n Cow::Borrowed(name) => Cow::Borrowed(&name[last_dot_at..]),\n Cow::Owned(ref name) => Cow::Owned(name[last_dot_at..].to_vec()),\n })\n}"} {"repo":"ripgrep","file":"crates/globset/src/pathutil.rs","line":59,"symbol":"normalize_path","kind":"function","lang":"rust","doc":"Normalizes a path to use `/` as a separator everywhere, even on platforms that recognize other characters as separators.","code":"pub(crate) fn normalize_path(path: Cow<'_, [u8]>) -> Cow<'_, [u8]> {\n // UNIX only uses /, so we're good.\n path\n}"} {"repo":"ripgrep","file":"crates/globset/src/pathutil.rs","line":67,"symbol":"normalize_path","kind":"function","lang":"rust","doc":"Normalizes a path to use `/` as a separator everywhere, even on platforms that recognize other characters as separators.","code":"pub(crate) fn normalize_path(mut path: Cow<[u8]>) -> Cow<[u8]> {\n use std::path::is_separator;\n\n for i in 0..path.len() {\n if path[i] == b'/' || !is_separator(char::from(path[i])) {\n continue;\n }\n path.to_mut()[i] = b'/';\n }\n path\n}"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":9,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n serializer: S,\n ) -> Result {\n serializer.serialize_str(self.glob())\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":17,"symbol":"GlobVisitor","kind":"type","lang":"rust","code":"struct GlobVisitor;"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":22,"symbol":"expecting","kind":"function","lang":"rust","code":"fn expecting(\n &self,\n formatter: &mut std::fmt::Formatter,\n ) -> std::fmt::Result {\n formatter.write_str(\"a glob pattern\")\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":29,"symbol":"visit_str","kind":"function","lang":"rust","code":"fn visit_str(self, v: &str) -> Result\n where\n E: Error,\n {\n Glob::new(v).map_err(serde::de::Error::custom)\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":38,"symbol":"deserialize","kind":"function","lang":"rust","code":"fn deserialize>(\n deserializer: D,\n ) -> Result {\n deserializer.deserialize_str(GlobVisitor)\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":45,"symbol":"GlobSetVisitor","kind":"type","lang":"rust","code":"struct GlobSetVisitor;"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":50,"symbol":"expecting","kind":"function","lang":"rust","code":"fn expecting(\n &self,\n formatter: &mut std::fmt::Formatter,\n ) -> std::fmt::Result {\n formatter.write_str(\"an array of glob patterns\")\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":57,"symbol":"visit_seq","kind":"function","lang":"rust","code":"fn visit_seq(self, mut seq: A) -> Result\n where\n A: SeqAccess<'de>,\n {\n let mut builder = GlobSetBuilder::new();\n while let Some(glob) = seq.next_element()? {\n builder.add(glob);\n }\n builder.build().map_err(serde::de::Error::custom)\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":70,"symbol":"deserialize","kind":"function","lang":"rust","code":"fn deserialize>(\n deserializer: D,\n ) -> Result {\n deserializer.deserialize_seq(GlobSetVisitor)\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":84,"symbol":"glob_deserialize_borrowed","kind":"function","lang":"rust","code":"fn glob_deserialize_borrowed() {\n let string = r#\"{\"markdown\": \"*.md\"}\"#;\n\n let map: HashMap =\n serde_json::from_str(&string).unwrap();\n assert_eq!(map[\"markdown\"], Glob::new(\"*.md\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":93,"symbol":"glob_deserialize_owned","kind":"function","lang":"rust","code":"fn glob_deserialize_owned() {\n let string = r#\"{\"markdown\": \"*.md\"}\"#;\n\n let v: serde_json::Value = serde_json::from_str(&string).unwrap();\n let map: HashMap = serde_json::from_value(v).unwrap();\n assert_eq!(map[\"markdown\"], Glob::new(\"*.md\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":102,"symbol":"glob_deserialize_error","kind":"function","lang":"rust","code":"fn glob_deserialize_error() {\n let string = r#\"{\"error\": \"[\"}\"#;\n\n let map = serde_json::from_str::>(&string);\n\n assert!(map.is_err());\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":111,"symbol":"glob_json_works","kind":"function","lang":"rust","code":"fn glob_json_works() {\n let test_glob = Glob::new(\"src/**/*.rs\").unwrap();\n\n let ser = serde_json::to_string(&test_glob).unwrap();\n assert_eq!(ser, \"\\\"src/**/*.rs\\\"\");\n\n let de: Glob = serde_json::from_str(&ser).unwrap();\n assert_eq!(test_glob, de);\n }"} {"repo":"ripgrep","file":"crates/globset/src/serde_impl.rs","line":122,"symbol":"glob_set_deserialize","kind":"function","lang":"rust","code":"fn glob_set_deserialize() {\n let j = r#\" [\"src/**/*.rs\", \"README.md\"] \"#;\n let set: GlobSet = serde_json::from_str(j).unwrap();\n assert!(set.is_match(\"src/lib.rs\"));\n assert!(!set.is_match(\"Cargo.lock\"));\n }"} {"repo":"ripgrep","file":"crates/grep/examples/simplegrep.rs","line":14,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n if let Err(err) = try_main() {\n eprintln!(\"{}\", err);\n process::exit(1);\n }\n}"} {"repo":"ripgrep","file":"crates/grep/examples/simplegrep.rs","line":21,"symbol":"try_main","kind":"function","lang":"rust","code":"fn try_main() -> Result<(), Box> {\n let mut args: Vec = env::args_os().collect();\n if args.len() < 2 {\n return Err(\"Usage: simplegrep [ ...]\".into());\n }\n if args.len() == 2 {\n args.push(OsString::from(\"./\"));\n }\n search(cli::pattern_from_os(&args[1])?, &args[2..])\n}"} {"repo":"ripgrep","file":"crates/grep/examples/simplegrep.rs","line":32,"symbol":"search","kind":"function","lang":"rust","code":"fn search(pattern: &str, paths: &[OsString]) -> Result<(), Box> {\n let matcher = RegexMatcher::new_line_matcher(&pattern)?;\n let mut searcher = SearcherBuilder::new()\n .binary_detection(BinaryDetection::quit(b'\\x00'))\n .line_number(false)\n .build();\n let mut printer = StandardBuilder::new()\n .color_specs(ColorSpecs::default_with_color())\n .build(cli::stdout(if std::io::stdout().is_terminal() {\n ColorChoice::Auto\n } else {\n ColorChoice::Never\n }));\n\n for path in paths {\n for result in WalkDir::new(path) {\n let dent = match result {\n Ok(dent) => dent,\n Err(err) => {\n eprintln!(\"{}\", err);\n continue;\n }\n };\n if !dent.file_type().is_file() {\n continue;\n }\n let result = searcher.search_path(\n &matcher,\n dent.path(),\n printer.sink_with_path(&matcher, dent.path()),\n );\n if let Err(err) = result {\n eprintln!(\"{}: {}\", dent.path().display(), err);\n }"} {"repo":"ripgrep","file":"crates/ignore/examples/walk.rs","line":5,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n let mut path = env::args().nth(1).unwrap();\n let mut parallel = false;\n let mut simple = false;\n let (tx, rx) = crossbeam_channel::bounded::(100);\n if path == \"parallel\" {\n path = env::args().nth(2).unwrap();\n parallel = true;\n } else if path == \"walkdir\" {\n path = env::args().nth(2).unwrap();\n simple = true;\n }\n\n let stdout_thread = std::thread::spawn(move || {\n let mut stdout = std::io::BufWriter::new(std::io::stdout());\n for dent in rx {\n stdout.write_all(&Vec::from_path_lossy(dent.path())).unwrap();\n stdout.write_all(b\"\\n\").unwrap();\n }\n });\n\n if parallel {\n let walker = WalkBuilder::new(path).threads(6).build_parallel();\n walker.run(|| {\n let tx = tx.clone();\n Box::new(move |result| {\n use ignore::WalkState::*;\n\n tx.send(DirEntry::Y(result.unwrap())).unwrap();\n Continue\n })\n });\n } else if simple {\n let walker = WalkDir::new(path);\n for result in walker {\n tx.send(DirEntry::X(result.unwrap())).unwrap();\n }\n } else {\n "} {"repo":"ripgrep","file":"crates/ignore/examples/walk.rs","line":52,"symbol":"DirEntry","kind":"type","lang":"rust","code":"enum DirEntry {\n X(walkdir::DirEntry),\n Y(ignore::DirEntry),\n}"} {"repo":"ripgrep","file":"crates/ignore/examples/walk.rs","line":58,"symbol":"path","kind":"function","lang":"rust","code":"fn path(&self) -> &Path {\n match *self {\n DirEntry::X(ref x) => x.path(),\n DirEntry::Y(ref y) => y.path(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/default_types.rs","line":353,"symbol":"default_types_are_sorted","kind":"function","lang":"rust","code":"fn default_types_are_sorted() {\n let mut names = DEFAULT_TYPES.iter().map(|(aliases, _)| aliases[0]);\n let Some(mut previous_name) = names.next() else {\n return;\n };\n for name in names {\n assert!(\n name > previous_name,\n r#\"\"{}\" should be sorted before \"{}\" in `DEFAULT_TYPES`\"#,\n name,\n previous_name\n );\n previous_name = name;\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/default_types.rs","line":370,"symbol":"default_types_aliases_are_sorted","kind":"function","lang":"rust","code":"fn default_types_aliases_are_sorted() {\n for (aliases, _) in DEFAULT_TYPES.iter() {\n assert!(\n aliases.is_sorted(),\n \"this alias list is not sorted: {aliases:?}\",\n );\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":38,"symbol":"IgnoreMatch","kind":"type","lang":"rust","doc":"IgnoreMatch represents information about where a match came from when using the `Ignore` matcher.","code":"pub(crate) struct IgnoreMatch<'a>(IgnoreMatchInner<'a>);"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":44,"symbol":"IgnoreMatchInner","kind":"type","lang":"rust","doc":"IgnoreMatchInner describes precisely where the match information came from. This is private to allow expansion to more matchers in the future.","code":"enum IgnoreMatchInner<'a> {\n Override(overrides::Glob<'a>),\n Gitignore(&'a gitignore::Glob),\n Types(types::Glob<'a>),\n Hidden,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":52,"symbol":"overrides","kind":"function","lang":"rust","code":"fn overrides(x: overrides::Glob<'a>) -> IgnoreMatch<'a> {\n IgnoreMatch(IgnoreMatchInner::Override(x))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":56,"symbol":"gitignore","kind":"function","lang":"rust","code":"fn gitignore(x: &'a gitignore::Glob) -> IgnoreMatch<'a> {\n IgnoreMatch(IgnoreMatchInner::Gitignore(x))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":60,"symbol":"types","kind":"function","lang":"rust","code":"fn types(x: types::Glob<'a>) -> IgnoreMatch<'a> {\n IgnoreMatch(IgnoreMatchInner::Types(x))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":64,"symbol":"hidden","kind":"function","lang":"rust","code":"fn hidden() -> IgnoreMatch<'static> {\n IgnoreMatch(IgnoreMatchInner::Hidden)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":72,"symbol":"IgnoreOptions","kind":"type","lang":"rust","doc":"Options for the ignore matcher, shared between the matcher itself and the builder.","code":"struct IgnoreOptions {\n /// Whether to ignore hidden file paths or not.\n hidden: bool,\n /// Whether to read .ignore files.\n ignore: bool,\n /// Whether to respect any ignore files in parent directories.\n parents: bool,\n /// Whether to read git's global gitignore file.\n git_global: bool,\n /// Whether to read .gitignore files.\n git_ignore: bool,\n /// Whether to read .git/info/exclude files.\n git_exclude: bool,\n /// Whether to ignore files case insensitively\n ignore_case_insensitive: bool,\n /// Whether a git repository must be present in order to apply any\n /// git-related ignore rules.\n require_git: bool,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":94,"symbol":"Ignore","kind":"type","lang":"rust","doc":"Ignore is a matcher useful for recursively walking one or more directories.","code":"pub(crate) struct Ignore {\n inner: Arc,\n // Parent matchers are cached independently of the path being walked, but\n // matching them still needs the canonicalized path originally passed to\n // `add_parents`. For example, when walking `/tmp/project/src`, parent\n // matchers use `/tmp/project/src` to rewrite `/tmp/project/src/foo.py`\n // before matching it against ignore files from `/tmp/project` and its\n // ancestors.\n //\n // For ripgrep itself, this means that `rg pat src tests` must rewrite\n // `src/foo` relative to `.../src`, and not whatever root was prepared\n // first.\n //\n // See: https://github.com/BurntSushi/ripgrep/pull/3420\n // See: https://github.com/BurntSushi/ripgrep/issues/3376\n // See: https://github.com/BurntSushi/ripgrep/issues/3419\n // See: https://github.com/BurntSushi/ripgrep/issues/3320\n absolute_base: Option>,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":115,"symbol":"IgnoreInner","kind":"type","lang":"rust","code":"struct IgnoreInner {\n /// A map of all existing directories that have already been\n /// compiled into matchers.\n ///\n /// Note that this is never used during matching, only when adding new\n /// parent directory matchers. This avoids needing to rebuild glob sets for\n /// parent directories if many paths are being searched.\n compiled: Arc>>>,\n /// The path to the directory that this matcher was built from.\n dir: PathBuf,\n /// An override matcher (default is empty).\n overrides: Arc,\n /// A file type matcher.\n types: Arc,\n /// The parent directory to match next.\n ///\n /// If this is the root directory or there are otherwise no more\n /// directories to match, then `parent` is `None`.\n parent: Option>,\n /// Whether this is an absolute parent matcher, as added by add_parent.\n is_absolute_parent: bool,\n /// The directory that gitignores should be interpreted relative to.\n ///\n /// Usually this is the directory containing the gitignore file. But in\n /// some cases, like for global gitignores or for gitignores specified\n /// explicitly, this "} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":171,"symbol":"path","kind":"function","lang":"rust","doc":"Return the directory path of this matcher.","code":"pub(crate) fn path(&self) -> &Path {\n &self.inner.dir\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":176,"symbol":"is_root","kind":"function","lang":"rust","doc":"Return true if this matcher has no parent.","code":"pub(crate) fn is_root(&self) -> bool {\n self.inner.parent.is_none()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":181,"symbol":"parent","kind":"function","lang":"rust","doc":"Return this matcher's parent, if one exists.","code":"pub(crate) fn parent(&self) -> Option {\n self.inner.parent.as_ref().map(|parent| Ignore {\n inner: parent.clone(),\n absolute_base: self.absolute_base.clone(),\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":192,"symbol":"add_parents","kind":"function","lang":"rust","doc":"Create a new `Ignore` matcher with the parent directories of `dir`. Note that this can only be called on an `Ignore` matcher with no parents (i.e., `is_root` returns `true`). This will panic otherwise.","code":"pub(crate) fn add_parents>(\n &self,\n path: P,\n ) -> (Ignore, Option) {\n if !self.inner.opts.parents\n && !self.inner.opts.git_ignore\n && !self.inner.opts.git_exclude\n && !self.inner.opts.git_global\n {\n // If we never need info from parent directories, then don't do\n // anything.\n return (self.clone(), None);\n }\n if !self.is_root() {\n panic!(\"Ignore::add_parents called on non-root matcher\");\n }\n let absolute_base = match path.as_ref().canonicalize() {\n Ok(path) => Arc::new(path),\n Err(_) => {\n // There's not much we can do here, so just return our\n // existing matcher. We drop the error to be consistent\n // with our general pattern of ignoring I/O errors when\n // processing ignore files.\n return (self.clone(), None);\n }\n };\n // List of parents, from child to root.\n let mut parents = vec![];\n let mut path = &**absolute_base;\n while let Some(parent) = path.parent() {\n parents.pus"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":268,"symbol":"add_child","kind":"function","lang":"rust","doc":"Since building the matcher may require reading from multiple files, it's possible that this method partially succeeds. Therefore, a matcher is always returned (which may match nothing) and an error is returned if it exists. Note that all I/O errors are completely ignored.","code":"pub(crate) fn add_child>(\n &self,\n dir: P,\n ) -> (Ignore, Option) {\n let (ig, err) = self.add_child_path(dir.as_ref());\n (\n Ignore {\n inner: Arc::new(ig),\n absolute_base: self.absolute_base.clone(),\n },\n err,\n )\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":284,"symbol":"add_child_with_entries","kind":"function","lang":"rust","doc":"Like add_child, but uses successful read_dir entries to reduce probing when discovering ignore files.","code":"pub(crate) fn add_child_with_entries>(\n &self,\n dir: P,\n entries: &[fs::DirEntry],\n ) -> (Ignore, Option) {\n let files = self.collect_ignore_files(entries);\n let (ig, err) = self.add_child_path_with_found_ignore_files(\n dir.as_ref(),\n Some(&files),\n );\n (\n Ignore {\n inner: Arc::new(ig),\n absolute_base: self.absolute_base.clone(),\n },\n err,\n )\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":304,"symbol":"add_child_path","kind":"function","lang":"rust","doc":"Like add_child, but takes a full path and returns an IgnoreInner.","code":"fn add_child_path(&self, dir: &Path) -> (IgnoreInner, Option) {\n self.add_child_path_with_found_ignore_files(dir, None)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":308,"symbol":"collect_ignore_files","kind":"function","lang":"rust","code":"fn collect_ignore_files(\n &self,\n entries: &[fs::DirEntry],\n ) -> IgnoreFilesFound {\n let custom_ignore_filenames = &self.inner.custom_ignore_filenames;\n let mut files = IgnoreFilesFound {\n has_ignore: false,\n has_git_ignore: false,\n has_git_dir: false,\n has_jj_dir: false,\n custom_ignore_files: vec![false; custom_ignore_filenames.len()],\n };\n for entry in entries {\n let file_name = entry.file_name();\n if file_name == OsStr::new(\".ignore\") {\n files.has_ignore = true;\n } else if file_name == OsStr::new(\".gitignore\") {\n files.has_git_ignore = true;\n } else if file_name == OsStr::new(\".git\") {\n files.has_git_dir = true;\n } else if file_name == OsStr::new(\".jj\") {\n files.has_jj_dir = true;\n }\n for (i, name) in custom_ignore_filenames.iter().enumerate() {\n if file_name == name.as_os_str() {\n files.custom_ignore_files[i] = true;\n }\n }\n }\n files\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":340,"symbol":"add_child_path_with_found_ignore_files","kind":"function","lang":"rust","code":"fn add_child_path_with_found_ignore_files(\n &self,\n dir: &Path,\n ignore_files_list: Option<&IgnoreFilesFound>,\n ) -> (IgnoreInner, Option) {\n let check_vcs_dir = self.inner.opts.require_git\n && (self.inner.opts.git_ignore || self.inner.opts.git_exclude);\n let git_type = if check_vcs_dir\n && ignore_files_list.is_none_or(|i| i.has_git_dir)\n {\n dir.join(\".git\").metadata().ok().map(|md| md.file_type())\n } else {\n None\n };\n let has_jj = check_vcs_dir\n && ignore_files_list.is_none_or(|i| i.has_jj_dir)\n && dir.join(\".jj\").exists();\n let has_git = check_vcs_dir && (git_type.is_some() || has_jj);\n\n let mut errs = PartialErrorBuilder::default();\n let custom_ig_matcher = if self\n .inner\n .custom_ignore_filenames\n .is_empty()\n {\n Gitignore::empty()\n } else {\n let custom_ignore_names: Vec<&OsString> = match ignore_files_list {\n None => self.inner.custom_ignore_filenames.iter().collect(),\n Some(m) => self\n .inner\n "} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":470,"symbol":"has_any_ignore_rules","kind":"function","lang":"rust","doc":"Returns true if at least one type of ignore rule should be matched.","code":"fn has_any_ignore_rules(&self) -> bool {\n let opts = self.inner.opts;\n let has_custom_ignore_files =\n !self.inner.custom_ignore_filenames.is_empty();\n let has_explicit_ignores = !self.inner.explicit_ignores.is_empty();\n\n opts.ignore\n || opts.git_global\n || opts.git_ignore\n || opts.git_exclude\n || has_custom_ignore_files\n || has_explicit_ignores\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":485,"symbol":"matched_dir_entry","kind":"function","lang":"rust","doc":"Like `matched`, but works with a directory entry instead.","code":"pub(crate) fn matched_dir_entry<'a>(\n &'a self,\n dent: &DirEntry,\n ) -> Match> {\n let m = self.matched(dent.path(), dent.is_dir());\n if m.is_none() && self.inner.opts.hidden && is_hidden_entry(dent) {\n return Match::Ignore(IgnoreMatch::hidden());\n }\n m\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":500,"symbol":"matched","kind":"function","lang":"rust","doc":"Returns a match indicating whether the given file path should be ignored or not. The match contains information about its origin.","code":"pub(crate) fn matched<'a, P: AsRef>(\n &'a self,\n path: P,\n is_dir: bool,\n ) -> Match> {\n // We need to be careful with our path. If it has a leading ./, then\n // strip it because it causes nothing but trouble.\n let mut path = path.as_ref();\n if let Some(p) = strip_prefix(\"./\", path) {\n path = p;\n }\n // Match against the override patterns. If an override matches\n // regardless of whether it's whitelist/ignore, then we quit and\n // return that result immediately. Overrides have the highest\n // precedence.\n if !self.inner.overrides.is_empty() {\n let mat = self\n .inner\n .overrides\n .matched(path, is_dir)\n .map(IgnoreMatch::overrides);\n if !mat.is_none() {\n return mat;\n }\n }\n let mut whitelisted = Match::None;\n if self.has_any_ignore_rules() {\n let mat = self.matched_ignore(path, is_dir);\n if mat.is_ignore() {\n return mat;\n } else if mat.is_whitelist() {\n whitelisted = mat;"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":548,"symbol":"matched_ignore","kind":"function","lang":"rust","doc":"Performs matching only on the ignore files for this directory and all parent directories.","code":"pub(crate) fn matched_ignore<'a>(\n &'a self,\n path: &Path,\n is_dir: bool,\n ) -> Match> {\n let (\n mut m_custom_ignore,\n mut m_ignore,\n mut m_gi,\n mut m_gi_exclude,\n mut m_explicit,\n ) = (Match::None, Match::None, Match::None, Match::None, Match::None);\n let any_git = !self.inner.opts.require_git\n || self.parents().any(|ig| ig.inner.has_git);\n let mut saw_git = false;\n for ig in self.parents().take_while(|ig| !ig.inner.is_absolute_parent)\n {\n if m_custom_ignore.is_none() {\n m_custom_ignore = ig\n .inner\n .custom_ignore_matcher\n .matched(path, is_dir)\n .map(IgnoreMatch::gitignore);\n }\n if m_ignore.is_none() {\n m_ignore = ig\n .inner\n .ignore_matcher\n .matched(path, is_dir)\n .map(IgnoreMatch::gitignore);\n }\n if any_git && !saw_git && m_gi.is_none() {\n m_gi = ig\n .inner\n "} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":688,"symbol":"parents","kind":"function","lang":"rust","doc":"Returns an iterator over parent ignore matchers, including this one.","code":"pub(crate) fn parents(&self) -> Parents<'_> {\n Parents(Some(IgnoreRef { inner: &self.inner }))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":694,"symbol":"absolute_base","kind":"function","lang":"rust","doc":"Returns the first absolute path of the first absolute parent, if one exists.","code":"fn absolute_base(&self) -> Option<&Path> {\n self.absolute_base.as_ref().map(|p| &***p)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":707,"symbol":"IgnoreFilesFound","kind":"type","lang":"rust","doc":"given directory. This is computed over the entire set of files in a directory instead of trying to stat each file individually. If a file is present, it's only then that we stat it for more information, instead of relying on the stat to determine its existence.","code":"struct IgnoreFilesFound {\n has_ignore: bool,\n has_git_ignore: bool,\n has_git_dir: bool,\n has_jj_dir: bool,\n custom_ignore_files: Vec,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":716,"symbol":"IgnoreRef","kind":"type","lang":"rust","code":"pub(crate) struct IgnoreRef<'a> {\n inner: &'a IgnoreInner,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":721,"symbol":"path","kind":"function","lang":"rust","code":"pub(crate) fn path(&self) -> &Path {\n &self.inner.dir\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":725,"symbol":"is_absolute_parent","kind":"function","lang":"rust","code":"pub(crate) fn is_absolute_parent(&self) -> bool {\n self.inner.is_absolute_parent\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":731,"symbol":"Parents","kind":"type","lang":"rust","doc":"An iterator over all parents of an ignore matcher, including itself.","code":"pub(crate) struct Parents<'a>(Option>);"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":736,"symbol":"next","kind":"function","lang":"rust","code":"fn next(&mut self) -> Option> {\n match self.0.take() {\n None => None,\n Some(ig) => {\n self.0 = ig\n .inner\n .parent\n .as_deref()\n .map(|inner| IgnoreRef { inner });\n Some(ig)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":753,"symbol":"IgnoreBuilder","kind":"type","lang":"rust","doc":"A builder for creating an Ignore matcher.","code":"pub(crate) struct IgnoreBuilder {\n /// The root directory path for this ignore matcher.\n dir: PathBuf,\n /// An override matcher (default is empty).\n overrides: Arc,\n /// A type matcher (default is empty).\n types: Arc,\n /// Explicit global ignore matchers.\n explicit_ignores: Vec,\n /// Ignore files in addition to .ignore.\n custom_ignore_filenames: Vec,\n /// The directory that gitignores should be interpreted relative to.\n ///\n /// Usually this is the directory containing the gitignore file. But in\n /// some cases, like for global gitignores or for gitignores specified\n /// explicitly, this should generally be set to the current working\n /// directory. This is only used for global gitignores or \"explicit\"\n /// gitignores.\n ///\n /// When `None`, global gitignores are ignored.\n global_gitignores_relative_to: Option,\n /// Ignore config.\n opts: IgnoreOptions,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":784,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for an `Ignore` matcher. It is likely a bug to use this without also calling `current_dir()` outside of tests. This isn't made mandatory because this is an internal abstraction and it's annoying to update tests.","code":"pub(crate) fn new() -> IgnoreBuilder {\n IgnoreBuilder {\n dir: Path::new(\"\").to_path_buf(),\n overrides: Arc::new(Override::empty()),\n types: Arc::new(Types::empty()),\n explicit_ignores: vec![],\n custom_ignore_filenames: vec![],\n global_gitignores_relative_to: None,\n opts: IgnoreOptions {\n hidden: true,\n ignore: true,\n parents: true,\n git_global: true,\n git_ignore: true,\n git_exclude: true,\n ignore_case_insensitive: false,\n require_git: true,\n },\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":809,"symbol":"build","kind":"function","lang":"rust","doc":"Builds a new `Ignore` matcher. The matcher returned won't match anything until ignore rules from directories are added to it.","code":"pub(crate) fn build(&self) -> Ignore {\n self.build_with_cwd(None)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":817,"symbol":"build_with_cwd","kind":"function","lang":"rust","doc":"Builds a new `Ignore` matcher using the given CWD directory. The matcher returned won't match anything until ignore rules from directories are added to it.","code":"pub(crate) fn build_with_cwd(&self, cwd: Option) -> Ignore {\n let global_gitignores_relative_to =\n cwd.or_else(|| self.global_gitignores_relative_to.clone());\n let git_global_matcher = if !self.opts.git_global {\n Gitignore::empty()\n } else if let Some(ref cwd) = global_gitignores_relative_to {\n let mut builder = GitignoreBuilder::new(cwd);\n builder\n .case_insensitive(self.opts.ignore_case_insensitive)\n .unwrap();\n let (gi, err) = builder.build_global();\n if let Some(err) = err {\n log::debug!(\"{}\", err);\n }\n gi\n } else {\n log::debug!(\n \"ignoring global gitignore file because CWD is not known\"\n );\n Gitignore::empty()\n };\n\n Ignore {\n inner: Arc::new(IgnoreInner {\n compiled: Arc::new(RwLock::new(HashMap::new())),\n dir: self.dir.clone(),\n overrides: self.overrides.clone(),\n types: self.types.clone(),\n parent: None,\n is_absolute_parent: true,\n gl"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":865,"symbol":"current_dir","kind":"function","lang":"rust","doc":"Set the current directory used for matching global gitignores.","code":"pub(crate) fn current_dir(\n &mut self,\n cwd: impl Into,\n ) -> &mut IgnoreBuilder {\n self.global_gitignores_relative_to = Some(cwd.into());\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":878,"symbol":"overrides","kind":"function","lang":"rust","doc":"Add an override matcher. By default, no override matcher is used. This overrides any previous setting.","code":"pub(crate) fn overrides(\n &mut self,\n overrides: Override,\n ) -> &mut IgnoreBuilder {\n self.overrides = Arc::new(overrides);\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":891,"symbol":"types","kind":"function","lang":"rust","doc":"Add a file type matcher. By default, no file type matcher is used. This overrides any previous setting.","code":"pub(crate) fn types(&mut self, types: Types) -> &mut IgnoreBuilder {\n self.types = Arc::new(types);\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":897,"symbol":"add_ignore","kind":"function","lang":"rust","doc":"Adds a new global ignore matcher from the ignore file path given.","code":"pub(crate) fn add_ignore(&mut self, ig: Gitignore) -> &mut IgnoreBuilder {\n self.explicit_ignores.push(ig);\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":908,"symbol":"add_custom_ignore_filename","kind":"function","lang":"rust","doc":"Add a custom ignore file name These ignore files have higher precedence than all other ignore files. When specifying multiple names, earlier names have lower precedence than later names.","code":"pub(crate) fn add_custom_ignore_filename>(\n &mut self,\n file_name: S,\n ) -> &mut IgnoreBuilder {\n self.custom_ignore_filenames.push(file_name.as_ref().to_os_string());\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":919,"symbol":"hidden","kind":"function","lang":"rust","doc":"Enables ignoring hidden files. This is enabled by default.","code":"pub(crate) fn hidden(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.hidden = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":925,"symbol":"is_hidden","kind":"function","lang":"rust","doc":"Whether ignoring hidden files is enabled or not.","code":"pub(crate) fn is_hidden(&self) -> bool {\n self.opts.hidden\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":935,"symbol":"ignore","kind":"function","lang":"rust","doc":"Enables reading `.ignore` files. `.ignore` files have the same semantics as `gitignore` files and are supported by search tools such as ripgrep and The Silver Searcher. This is enabled by default.","code":"pub(crate) fn ignore(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.ignore = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":946,"symbol":"parents","kind":"function","lang":"rust","doc":"Enables reading ignore files from parent directories. If this is enabled, then .gitignore files in parent directories of each file path given are respected. Otherwise, they are ignored. This is enabled by default.","code":"pub(crate) fn parents(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.parents = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":959,"symbol":"git_global","kind":"function","lang":"rust","doc":"Its precedence is lower than both normal `.gitignore` files and `.git/info/exclude` files. This overwrites any previous global gitignore setting. This is enabled by default.","code":"pub(crate) fn git_global(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.git_global = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":970,"symbol":"git_ignore","kind":"function","lang":"rust","doc":"Enables reading `.gitignore` files. `.gitignore` files have match semantics as described in the `gitignore` man page. This is enabled by default.","code":"pub(crate) fn git_ignore(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.git_ignore = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":981,"symbol":"git_exclude","kind":"function","lang":"rust","doc":"Enables reading `.git/info/exclude` files. `.git/info/exclude` files have match semantics as described in the `gitignore` man page. This is enabled by default.","code":"pub(crate) fn git_exclude(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.git_exclude = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":991,"symbol":"require_git","kind":"function","lang":"rust","doc":"Whether a git repository is required to apply git-related ignore rules (global rules, .gitignore and local exclude rules). When disabled, git-related ignore rules are applied even when searching outside a git repository.","code":"pub(crate) fn require_git(&mut self, yes: bool) -> &mut IgnoreBuilder {\n self.opts.require_git = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":999,"symbol":"ignore_case_insensitive","kind":"function","lang":"rust","doc":"Process ignore files case insensitively This is disabled by default.","code":"pub(crate) fn ignore_case_insensitive(\n &mut self,\n yes: bool,\n ) -> &mut IgnoreBuilder {\n self.opts.ignore_case_insensitive = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1016,"symbol":"create_gitignore","kind":"function","lang":"rust","doc":"The matcher is meant to match files below `dir`. Ignore globs are extracted from each of the file names relative to `dir_for_ignorefile` in the order given (earlier names have lower precedence than later names). I/O errors are ignored.","code":"pub(crate) fn create_gitignore>(\n dir: &Path,\n dir_for_ignorefile: &Path,\n names: &[T],\n case_insensitive: bool,\n) -> (Gitignore, Option) {\n let mut builder = GitignoreBuilder::new(dir);\n let mut errs = PartialErrorBuilder::default();\n builder.case_insensitive(case_insensitive).unwrap();\n for name in names {\n let gipath = dir_for_ignorefile.join(name.as_ref());\n // This check is not necessary, but is added for performance. Namely,\n // a simple stat call checking for existence can often be just a bit\n // quicker than actually trying to open a file. Since the number of\n // directories without ignore files likely greatly exceeds the number\n // with ignore files, this check generally makes sense.\n //\n // However, until demonstrated otherwise, we speculatively do not do\n // this on Windows since Windows is notorious for having slow file\n // system operations. Namely, it's not clear whether this analysis\n // makes sense on Windows.\n //\n // For more details: https://github.com/BurntSushi/ripgrep/pull/1381\n if cfg!(windows) || gipath.exists() {\n "} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1061,"symbol":"resolve_git_commondir","kind":"function","lang":"rust","doc":"This is the directory that may contain a private ignore file \"info/exclude\". Unlike git, this function does *not* read environment variables GIT_DIR and GIT_COMMON_DIR, because it is not clear how to use them when multiple repositories are searched. Some I/O errors are ignored.","code":"fn resolve_git_commondir(\n dir: &Path,\n git_type: Option,\n) -> Result> {\n let git_dir_path = || dir.join(\".git\");\n let git_dir = git_dir_path();\n if !git_type.map_or(false, |ft| ft.is_file()) {\n return Ok(git_dir);\n }\n let file = match File::open(git_dir) {\n Ok(file) => io::BufReader::new(file),\n Err(err) => {\n return Err(Some(Error::Io(err).with_path(git_dir_path())));\n }\n };\n let dot_git_line = match file.lines().next() {\n Some(Ok(line)) => line,\n Some(Err(err)) => {\n return Err(Some(Error::Io(err).with_path(git_dir_path())));\n }\n None => return Err(None),\n };\n if !dot_git_line.starts_with(\"gitdir: \") {\n return Err(None);\n }\n let real_git_dir = PathBuf::from(&dot_git_line[\"gitdir: \".len()..]);\n let git_commondir_file = || real_git_dir.join(\"commondir\");\n let file = match File::open(git_commondir_file()) {\n Ok(file) => io::BufReader::new(file),\n Err(_) => return Err(None),\n };\n let commondir_line = match file.lines().next() {\n Some(Ok(line)) => line,\n Some(Err(err)) => {\n retu"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1109,"symbol":"strip_if_is_prefix","kind":"function","lang":"rust","doc":"Strips `prefix` from `path` if it's a prefix, otherwise returns `path` unchanged.","code":"fn strip_if_is_prefix<'a, P: AsRef + ?Sized>(\n prefix: &'a P,\n path: &'a Path,\n) -> &'a Path {\n strip_prefix(prefix, path).map_or(path, |p| p)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1124,"symbol":"wfile","kind":"function","lang":"rust","code":"fn wfile>(path: P, contents: &str) {\n let mut file = std::fs::File::create(path).unwrap();\n file.write_all(contents.as_bytes()).unwrap();\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1129,"symbol":"mkdirp","kind":"function","lang":"rust","code":"fn mkdirp>(path: P) {\n std::fs::create_dir_all(path).unwrap();\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1133,"symbol":"partial","kind":"function","lang":"rust","code":"fn partial(err: Error) -> Vec {\n match err {\n Error::Partial(errs) => errs,\n _ => panic!(\"expected partial error but got {:?}\", err),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1140,"symbol":"tmpdir","kind":"function","lang":"rust","code":"fn tmpdir() -> TempDir {\n TempDir::new().unwrap()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1145,"symbol":"explicit_ignore","kind":"function","lang":"rust","code":"fn explicit_ignore() {\n let td = tmpdir();\n wfile(td.path().join(\"not-an-ignore\"), \"foo\\n!bar\");\n\n let (gi, err) = Gitignore::new(td.path().join(\"not-an-ignore\"));\n assert!(err.is_none());\n let (ig, err) =\n IgnoreBuilder::new().add_ignore(gi).build().add_child(td.path());\n assert!(err.is_none());\n assert!(ig.matched(\"foo\", false).is_ignore());\n assert!(ig.matched(\"bar\", false).is_whitelist());\n assert!(ig.matched(\"baz\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1160,"symbol":"git_exclude","kind":"function","lang":"rust","code":"fn git_exclude() {\n let td = tmpdir();\n mkdirp(td.path().join(\".git/info\"));\n wfile(td.path().join(\".git/info/exclude\"), \"foo\\n!bar\");\n\n let (ig, err) = IgnoreBuilder::new().build().add_child(td.path());\n assert!(err.is_none());\n assert!(ig.matched(\"foo\", false).is_ignore());\n assert!(ig.matched(\"bar\", false).is_whitelist());\n assert!(ig.matched(\"baz\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1173,"symbol":"gitignore","kind":"function","lang":"rust","code":"fn gitignore() {\n let td = tmpdir();\n mkdirp(td.path().join(\".git\"));\n wfile(td.path().join(\".gitignore\"), \"foo\\n!bar\");\n\n let (ig, err) = IgnoreBuilder::new().build().add_child(td.path());\n assert!(err.is_none());\n assert!(ig.matched(\"foo\", false).is_ignore());\n assert!(ig.matched(\"bar\", false).is_whitelist());\n assert!(ig.matched(\"baz\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1186,"symbol":"gitignore_with_jj","kind":"function","lang":"rust","code":"fn gitignore_with_jj() {\n let td = tmpdir();\n mkdirp(td.path().join(\".jj\"));\n wfile(td.path().join(\".gitignore\"), \"foo\\n!bar\");\n\n let (ig, err) = IgnoreBuilder::new().build().add_child(td.path());\n assert!(err.is_none());\n assert!(ig.matched(\"foo\", false).is_ignore());\n assert!(ig.matched(\"bar\", false).is_whitelist());\n assert!(ig.matched(\"baz\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/dir.rs","line":1199,"symbol":"gitignore_no_git","kind":"function","lang":"rust","code":"fn gitignore_no_git() {\n let td = tmpdir();\n wfile(td.path().join(\".gitignore\"), \"foo\\n!bar\");\n\n let (ig, err) = IgnoreBuilder::new().build().add_child(td.path());\n assert!(err.is_none());\n assert!(ig.matched(\"foo\", false).is_none());\n assert!(ig.matched(\"bar\", false).is_none());\n assert!(ig.matched(\"baz\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":32,"symbol":"Glob","kind":"type","lang":"rust","doc":"Glob represents a single glob in a gitignore file. This is used to report information about the highest precedent glob that matched in one or more gitignore files.","code":"pub struct Glob {\n /// The file path that this glob was extracted from.\n from: Option,\n /// The original glob string.\n original: String,\n /// The actual glob string used to convert to a regex.\n actual: String,\n /// Whether this is a whitelisted glob or not.\n is_whitelist: bool,\n /// Whether this glob should only match directories or not.\n is_only_dir: bool,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":47,"symbol":"from","kind":"function","lang":"rust","doc":"Returns the file path that defined this glob.","code":"pub fn from(&self) -> Option<&Path> {\n self.from.as_ref().map(|p| &**p)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":52,"symbol":"original","kind":"function","lang":"rust","doc":"The original glob as it was defined in a gitignore file.","code":"pub fn original(&self) -> &str {\n &self.original\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":58,"symbol":"actual","kind":"function","lang":"rust","doc":"The actual glob that was compiled to respect gitignore semantics.","code":"pub fn actual(&self) -> &str {\n &self.actual\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":63,"symbol":"is_whitelist","kind":"function","lang":"rust","doc":"Whether this was a whitelisted glob or not.","code":"pub fn is_whitelist(&self) -> bool {\n self.is_whitelist\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":68,"symbol":"is_only_dir","kind":"function","lang":"rust","doc":"Whether this glob must match a directory or not.","code":"pub fn is_only_dir(&self) -> bool {\n self.is_only_dir\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":73,"symbol":"has_doublestar_prefix","kind":"function","lang":"rust","doc":"Returns true if and only if this glob has a `**/` prefix.","code":"fn has_doublestar_prefix(&self) -> bool {\n self.actual.starts_with(\"**/\") || self.actual == \"**\"\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":81,"symbol":"Gitignore","kind":"type","lang":"rust","doc":"Gitignore is a matcher for the globs in one or more gitignore files in the same directory.","code":"pub struct Gitignore {\n set: GlobSet,\n root: PathBuf,\n globs: Vec,\n num_ignores: u64,\n num_whitelists: u64,\n matches: Option>>>,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":103,"symbol":"new","kind":"function","lang":"rust","doc":"This always returns a valid matcher, even if it's empty. In particular, a Gitignore file can be partially valid, e.g., when one glob is invalid but the rest aren't. Note that I/O errors are ignored. For more granular control over errors, use `GitignoreBuilder`.","code":"pub fn new>(\n gitignore_path: P,\n ) -> (Gitignore, Option) {\n let path = gitignore_path.as_ref();\n let parent = path.parent().unwrap_or(Path::new(\"/\"));\n let mut builder = GitignoreBuilder::new(parent);\n let mut errs = PartialErrorBuilder::default();\n errs.maybe_push_ignore_io(builder.add(path));\n match builder.build() {\n Ok(gi) => (gi, errs.into_error_option()),\n Err(err) => {\n errs.push(err);\n (Gitignore::empty(), errs.into_error_option())\n }\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":141,"symbol":"global","kind":"function","lang":"rust","doc":"Git's config file location is `$HOME/.gitconfig`. If `$HOME/.gitconfig` does not exist or does not specify `core.excludesFile`, then `$XDG_CONFIG_HOME/git/ignore` is read. If `$XDG_CONFIG_HOME` is not set or is empty, then `$HOME/.config/git/ignore` is used instead.","code":"pub fn global() -> (Gitignore, Option) {\n match std::env::current_dir() {\n Ok(cwd) => GitignoreBuilder::new(cwd).build_global(),\n Err(err) => (Gitignore::empty(), Some(err.into())),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":151,"symbol":"empty","kind":"function","lang":"rust","doc":"Creates a new empty gitignore matcher that never matches anything. Its path is empty.","code":"pub fn empty() -> Gitignore {\n Gitignore {\n set: GlobSet::empty(),\n root: PathBuf::from(\"\"),\n globs: vec![],\n num_ignores: 0,\n num_whitelists: 0,\n matches: None,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":165,"symbol":"path","kind":"function","lang":"rust","doc":"Returns the directory containing this gitignore matcher. All matches are done relative to this path.","code":"pub fn path(&self) -> &Path {\n &*self.root\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":171,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if and only if this gitignore has zero globs, and therefore never matches any file path.","code":"pub fn is_empty(&self) -> bool {\n self.set.is_empty()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":177,"symbol":"len","kind":"function","lang":"rust","doc":"Returns the total number of globs, which should be equivalent to `num_ignores + num_whitelists`.","code":"pub fn len(&self) -> usize {\n self.set.len()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":182,"symbol":"num_ignores","kind":"function","lang":"rust","doc":"Returns the total number of ignore globs.","code":"pub fn num_ignores(&self) -> u64 {\n self.num_ignores\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":187,"symbol":"num_whitelists","kind":"function","lang":"rust","doc":"Returns the total number of whitelisted globs.","code":"pub fn num_whitelists(&self) -> u64 {\n self.num_whitelists\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":202,"symbol":"matched","kind":"function","lang":"rust","doc":"The given path is matched relative to the path given when building the matcher. Specifically, before matching `path`, its prefix (as determined by a common suffix of the directory containing this gitignore) is stripped. If there is no common suffix/prefix overlap, then `path` is assumed to be relative to this matcher.","code":"pub fn matched>(\n &self,\n path: P,\n is_dir: bool,\n ) -> Match<&Glob> {\n if self.is_empty() {\n return Match::None;\n }\n self.matched_stripped(self.strip(path.as_ref()), is_dir)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":234,"symbol":"matched_path_or_any_parents","kind":"function","lang":"rust","doc":"then `path` is assumed to be relative to this matcher. # Panics This method panics if the given file path is not under the root path of this matcher.","code":"pub fn matched_path_or_any_parents>(\n &self,\n path: P,\n is_dir: bool,\n ) -> Match<&Glob> {\n if self.is_empty() {\n return Match::None;\n }\n let mut path = self.strip(path.as_ref());\n assert!(!path.has_root(), \"path is expected to be under the root\");\n\n match self.matched_stripped(path, is_dir) {\n Match::None => (), // walk up\n a_match => return a_match,\n }\n while let Some(parent) = path.parent() {\n match self.matched_stripped(parent, /* is_dir */ true) {\n Match::None => path = parent, // walk up\n a_match => return a_match,\n }\n }\n Match::None\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":259,"symbol":"matched_stripped","kind":"function","lang":"rust","doc":"Like matched, but takes a path that has already been stripped.","code":"fn matched_stripped>(\n &self,\n path: P,\n is_dir: bool,\n ) -> Match<&Glob> {\n if self.is_empty() {\n return Match::None;\n }\n let path = path.as_ref();\n let mut matches = self.matches.as_ref().unwrap().get();\n let candidate = Candidate::new(path);\n self.set.matches_candidate_into(&candidate, &mut *matches);\n for &i in matches.iter().rev() {\n let glob = &self.globs[i];\n if !glob.is_only_dir() || is_dir {\n return if glob.is_whitelist() {\n Match::Whitelist(glob)\n } else {\n Match::Ignore(glob)\n };\n }\n }\n Match::None\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":286,"symbol":"strip","kind":"function","lang":"rust","doc":"Strips the given path such that it's suitable for matching with this gitignore matcher.","code":"fn strip<'a, P: 'a + AsRef + ?Sized>(\n &'a self,\n path: &'a P,\n ) -> &'a Path {\n let mut path = path.as_ref();\n // A leading ./ is completely superfluous. We also strip it from\n // our gitignore root path, so we need to strip it from our candidate\n // path too.\n if let Some(p) = strip_prefix(\"./\", path) {\n path = p;\n }\n // Strip any common prefix between the candidate path and the root\n // of the gitignore, to make sure we get relative matching right.\n // BUT, a file name might not have any directory components to it,\n // in which case, we don't want to accidentally strip any part of the\n // file name.\n //\n // As an additional special case, if the root is just `.`, then we\n // shouldn't try to strip anything, e.g., when path begins with a `.`.\n if self.root != Path::new(\".\") && !is_file_name(path) {\n if let Some(p) = strip_prefix(&self.root, path) {\n path = p;\n // If we're left with a leading slash, get rid of it.\n if let Some(p) = strip_prefix(\"/\", path) {\n path = p;\n "} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":320,"symbol":"GitignoreBuilder","kind":"type","lang":"rust","doc":"Builds a matcher for a single set of globs from a .gitignore file.","code":"pub struct GitignoreBuilder {\n builder: GlobSetBuilder,\n root: PathBuf,\n globs: Vec,\n case_insensitive: bool,\n allow_unclosed_class: bool,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":335,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for a gitignore file. The path given should be the path at which the globs for this gitignore file should be matched. Note that paths are always matched relative to the root path given here. Generally, the root path should correspond to the *directory* containing a `.gitignore` file.","code":"pub fn new>(root: P) -> GitignoreBuilder {\n let root = root.as_ref();\n GitignoreBuilder {\n builder: GlobSetBuilder::new(),\n root: strip_prefix(\"./\", root).unwrap_or(root).to_path_buf(),\n globs: vec![],\n case_insensitive: false,\n allow_unclosed_class: true,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":349,"symbol":"build","kind":"function","lang":"rust","doc":"Builds a new matcher from the globs added so far. Once a matcher is built, no new globs can be added to it.","code":"pub fn build(&self) -> Result {\n let nignore = self.globs.iter().filter(|g| !g.is_whitelist()).count();\n let nwhite = self.globs.iter().filter(|g| g.is_whitelist()).count();\n let set = self\n .builder\n .build()\n .map_err(|err| Error::Glob { glob: None, err: err.to_string() })?;\n Ok(Gitignore {\n set,\n root: self.root.clone(),\n globs: self.globs.clone(),\n num_ignores: nignore as u64,\n num_whitelists: nwhite as u64,\n matches: Some(Arc::new(\n Pool::with_available_parallelism_capacity(|| vec![]),\n )),\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":377,"symbol":"build_global","kind":"function","lang":"rust","doc":"This consumes ownership of the builder unlike `build` because it must mutate the builder to add the global gitignore globs. Note that this ignores the path given to this builder's constructor and instead derives the path automatically from git's global configuration.","code":"pub fn build_global(mut self) -> (Gitignore, Option) {\n match gitconfig_excludes_path() {\n None => (Gitignore::empty(), None),\n Some(path) => {\n if !path.is_file() {\n (Gitignore::empty(), None)\n } else {\n let mut errs = PartialErrorBuilder::default();\n errs.maybe_push_ignore_io(self.add(path));\n match self.build() {\n Ok(gi) => (gi, errs.into_error_option()),\n Err(err) => {\n errs.push(err);\n (Gitignore::empty(), errs.into_error_option())\n }\n }\n }\n }\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":405,"symbol":"add","kind":"function","lang":"rust","doc":"The file given should be formatted as a `gitignore` file. Note that partial errors can be returned. For example, if there was a problem adding one glob, an error for that will be returned, but all other valid globs will still be added.","code":"pub fn add>(&mut self, path: P) -> Option {\n let path = path.as_ref();\n let file = match File::open(path) {\n Err(err) => return Some(Error::Io(err).with_path(path)),\n Ok(file) => file,\n };\n log::debug!(\"opened gitignore file: {}\", path.display());\n let rdr = BufReader::new(file);\n let mut errs = PartialErrorBuilder::default();\n for (i, line) in rdr.lines().enumerate() {\n let lineno = (i + 1) as u64;\n let line = match line {\n Ok(line) => line,\n Err(err) => {\n errs.push(Error::Io(err).tagged(path, lineno));\n break;\n }\n };\n\n // Match Git's handling of .gitignore files that begin with the Unicode BOM\n const UTF8_BOM: &str = \"\\u{feff}\";\n let line =\n if i == 0 { line.trim_start_matches(UTF8_BOM) } else { &line };\n\n if let Err(err) = self.add_line(Some(path.to_path_buf()), &line) {\n errs.push(err.tagged(path, lineno));\n }\n }\n errs.into_error_option()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":443,"symbol":"add_str","kind":"function","lang":"rust","doc":"Add each glob line from the string given. If this string came from a particular `gitignore` file, then its path should be provided here. The string given should be formatted as a `gitignore` file.","code":"fn add_str(\n &mut self,\n from: Option,\n gitignore: &str,\n ) -> Result<&mut GitignoreBuilder, Error> {\n for line in gitignore.lines() {\n self.add_line(from.clone(), line)?;\n }\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":460,"symbol":"add_line","kind":"function","lang":"rust","doc":"Add a line from a gitignore file to this builder. If this line came from a particular `gitignore` file, then its path should be provided here. If the line could not be parsed as a glob, then an error is returned.","code":"pub fn add_line(\n &mut self,\n from: Option,\n mut line: &str,\n ) -> Result<&mut GitignoreBuilder, Error> {\n #![allow(deprecated)]\n\n if line.starts_with(\"#\") {\n return Ok(self);\n }\n if !line.ends_with(\"\\\\ \") {\n line = line.trim_right();\n }\n if line.is_empty() {\n return Ok(self);\n }\n let mut glob = Glob {\n from,\n original: line.to_string(),\n actual: String::new(),\n is_whitelist: false,\n is_only_dir: false,\n };\n let mut is_absolute = false;\n if line.starts_with(\"\\\\!\") || line.starts_with(\"\\\\#\") {\n line = &line[1..];\n is_absolute = line.chars().nth(0) == Some('/');\n } else {\n if line.starts_with(\"!\") {\n glob.is_whitelist = true;\n line = &line[1..];\n }\n if line.starts_with(\"/\") {\n // `man gitignore` says that if a glob starts with a slash,\n // then the glob can only match the beginning of a path\n // (relative to the location of gitignore). We achieve this by\n"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":549,"symbol":"case_insensitive","kind":"function","lang":"rust","doc":"Toggle whether the globs should be matched case insensitively or not. When this option is changed, only globs added after the change will be affected. This is disabled by default.","code":"pub fn case_insensitive(\n &mut self,\n yes: bool,\n ) -> Result<&mut GitignoreBuilder, Error> {\n // TODO: This should not return a `Result`. Fix this in the next semver\n // release.\n self.case_insensitive = yes;\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":571,"symbol":"allow_unclosed_class","kind":"function","lang":"rust","doc":"By default, this is true in order to match established `gitignore` semantics. Generally speaking, enabling this leads to worse failure modes since the glob parser becomes more permissive. You might want to enable this when compatibility (e.g., with POSIX glob implementations) is more important than good error messages.","code":"pub fn allow_unclosed_class(\n &mut self,\n yes: bool,\n ) -> &mut GitignoreBuilder {\n self.allow_unclosed_class = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":583,"symbol":"gitconfig_excludes_path","kind":"function","lang":"rust","doc":"Return the file path of the current environment's global gitignore file. Note that the file path returned may not exist.","code":"pub fn gitconfig_excludes_path() -> Option {\n // When GIT_CONFIG_GLOBAL is set, it replaces both $HOME/.gitconfig and\n // $XDG_CONFIG_HOME/git/config (per git 2.32+). Otherwise, git supports\n // $HOME/.gitconfig and $XDG_CONFIG_HOME/git/config simultaneously, where\n // $HOME/.gitconfig takes precedent.\n gitconfig_global_env_contents()\n .and_then(|x| parse_excludes_file(&x))\n .or_else(|| {\n gitconfig_home_contents().and_then(|x| parse_excludes_file(&x))\n })\n .or_else(|| {\n gitconfig_xdg_contents().and_then(|x| parse_excludes_file(&x))\n })\n // System-level config has the lowest priority for core.excludesFile.\n // GIT_CONFIG_SYSTEM overrides the default /etc/gitconfig path.\n .or_else(|| {\n gitconfig_system_contents().and_then(|x| parse_excludes_file(&x))\n })\n .or_else(excludes_file_default)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":606,"symbol":"gitconfig_global_env_contents","kind":"function","lang":"rust","doc":"Returns the file contents of git's global config file from the path specified by the `GIT_CONFIG_GLOBAL` environment variable.","code":"fn gitconfig_global_env_contents() -> Option> {\n let path = std::env::var_os(\"GIT_CONFIG_GLOBAL\").map(PathBuf::from)?;\n if path.as_os_str().is_empty() {\n return None;\n }\n let mut file = BufReader::new(File::open(path).ok()?);\n let mut contents = vec![];\n file.read_to_end(&mut contents).ok().map(|_| contents)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":619,"symbol":"gitconfig_system_contents","kind":"function","lang":"rust","doc":"Returns the file contents of git's system-level config file. Checks `GIT_CONFIG_SYSTEM` first, then falls back to `/etc/gitconfig`.","code":"fn gitconfig_system_contents() -> Option> {\n let path = std::env::var_os(\"GIT_CONFIG_SYSTEM\")\n .map(PathBuf::from)\n .filter(|x| !x.as_os_str().is_empty())\n .unwrap_or_else(|| PathBuf::from(\"/etc/gitconfig\"));\n let mut file = BufReader::new(File::open(path).ok()?);\n let mut contents = vec![];\n file.read_to_end(&mut contents).ok().map(|_| contents)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":631,"symbol":"gitconfig_home_contents","kind":"function","lang":"rust","doc":"Returns the file contents of git's global config file, if one exists, in the user's home directory.","code":"fn gitconfig_home_contents() -> Option> {\n let home = home_dir()?;\n let mut file = BufReader::new(File::open(home.join(\".gitconfig\")).ok()?);\n let mut contents = vec![];\n file.read_to_end(&mut contents).ok().map(|_| contents)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":640,"symbol":"gitconfig_xdg_contents","kind":"function","lang":"rust","doc":"Returns the file contents of git's global config file, if one exists, in the user's XDG_CONFIG_HOME directory.","code":"fn gitconfig_xdg_contents() -> Option> {\n let path = std::env::var_os(\"XDG_CONFIG_HOME\")\n .map(PathBuf::from)\n .filter(|x| !x.as_os_str().is_empty())\n .or_else(|| home_dir().map(|p| p.join(\".config\")))\n .map(|x| x.join(\"git/config\"))?;\n let mut file = BufReader::new(File::open(path).ok()?);\n let mut contents = vec![];\n file.read_to_end(&mut contents).ok().map(|_| contents)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":654,"symbol":"excludes_file_default","kind":"function","lang":"rust","doc":"Returns the default file path for a global .gitignore file. Specifically, this respects XDG_CONFIG_HOME.","code":"fn excludes_file_default() -> Option {\n std::env::var_os(\"XDG_CONFIG_HOME\")\n .map(PathBuf::from)\n .filter(|x| !x.as_os_str().is_empty())\n .or_else(|| home_dir().map(|p| p.join(\".config\")))\n .map(|x| x.join(\"git/ignore\"))\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":664,"symbol":"parse_excludes_file","kind":"function","lang":"rust","doc":"Extract git's `core.excludesfile` config setting from the raw file contents given.","code":"fn parse_excludes_file(data: &[u8]) -> Option {\n use std::sync::OnceLock;\n\n use regex_automata::{meta::Regex, util::syntax};\n\n // N.B. This is the lazy approach, and isn't technically correct, but\n // probably works in more circumstances. I guess we would ideally have\n // a full INI parser. Yuck.\n static RE: OnceLock = OnceLock::new();\n let re = RE.get_or_init(|| {\n Regex::builder()\n .configure(Regex::config().utf8_empty(false))\n .syntax(syntax::Config::new().utf8(false))\n .build(r#\"(?im-u)^\\s*excludesfile\\s*=\\s*\"?\\s*(\\S+?)\\s*\"?\\s*$\"#)\n .unwrap()\n });\n // We don't care about amortizing allocs here I think. This should only\n // be called ~once per traversal or so? (Although it's not guaranteed...)\n let mut caps = re.create_captures();\n re.captures(data, &mut caps);\n let span = caps.get_group(1)?;\n let candidate = &data[span];\n std::str::from_utf8(candidate).ok().map(|s| PathBuf::from(expand_tilde(s)))\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":690,"symbol":"expand_tilde","kind":"function","lang":"rust","doc":"Expands ~ in file paths to the value of $HOME.","code":"fn expand_tilde(path: &str) -> String {\n let home = match home_dir() {\n None => return path.to_string(),\n Some(home) => home.to_string_lossy().into_owned(),\n };\n path.replace(\"~\", &home)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":699,"symbol":"home_dir","kind":"function","lang":"rust","doc":"Returns the location of the user's home directory.","code":"fn home_dir() -> Option {\n // We're fine with using std::env::home_dir for now. Its bugs are, IMO,\n // pretty minor corner cases.\n #![allow(deprecated)]\n std::env::home_dir()\n}"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":712,"symbol":"gi_from_str","kind":"function","lang":"rust","code":"fn gi_from_str>(root: P, s: &str) -> Gitignore {\n let mut builder = GitignoreBuilder::new(root);\n builder.add_str(None, s).unwrap();\n builder.build().unwrap()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":816,"symbol":"bytes","kind":"function","lang":"rust","code":"fn bytes(s: &str) -> Vec {\n s.to_string().into_bytes()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":820,"symbol":"path_string","kind":"function","lang":"rust","code":"fn path_string>(path: P) -> String {\n path.as_ref().to_str().unwrap().to_string()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":825,"symbol":"parse_excludes_file1","kind":"function","lang":"rust","code":"fn parse_excludes_file1() {\n let data = bytes(\"[core]\\nexcludesFile = /foo/bar\");\n let got = super::parse_excludes_file(&data).unwrap();\n assert_eq!(path_string(got), \"/foo/bar\");\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":832,"symbol":"parse_excludes_file2","kind":"function","lang":"rust","code":"fn parse_excludes_file2() {\n let data = bytes(\"[core]\\nexcludesFile = ~/foo/bar\");\n let got = super::parse_excludes_file(&data).unwrap();\n assert_eq!(path_string(got), super::expand_tilde(\"~/foo/bar\"));\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":839,"symbol":"parse_excludes_file3","kind":"function","lang":"rust","code":"fn parse_excludes_file3() {\n let data = bytes(\"[core]\\nexcludeFile = /foo/bar\");\n assert!(super::parse_excludes_file(&data).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":845,"symbol":"parse_excludes_file4","kind":"function","lang":"rust","code":"fn parse_excludes_file4() {\n let data = bytes(\"[core]\\nexcludesFile = \\\"~/foo/bar\\\"\");\n let got = super::parse_excludes_file(&data);\n assert_eq!(\n path_string(got.unwrap()),\n super::expand_tilde(\"~/foo/bar\")\n );\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":855,"symbol":"parse_excludes_file5","kind":"function","lang":"rust","code":"fn parse_excludes_file5() {\n let data = bytes(\"[core]\\nexcludesFile = \\\" \\\"~/foo/bar \\\" \\\"\");\n assert!(super::parse_excludes_file(&data).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":862,"symbol":"regression_106","kind":"function","lang":"rust","doc":"See: https://github.com/BurntSushi/ripgrep/issues/106","code":"fn regression_106() {\n gi_from_str(\"/\", \" \");\n }"} {"repo":"ripgrep","file":"crates/ignore/src/gitignore.rs","line":867,"symbol":"case_insensitive","kind":"function","lang":"rust","code":"fn case_insensitive() {\n let gi = GitignoreBuilder::new(ROOT)\n .case_insensitive(true)\n .unwrap()\n .add_str(None, \"*.html\")\n .unwrap()\n .build()\n .unwrap();\n assert!(gi.matched(\"foo.html\", false).is_ignore());\n assert!(gi.matched(\"foo.HTML\", false).is_ignore());\n assert!(!gi.matched(\"foo.htm\", false).is_ignore());\n assert!(!gi.matched(\"foo.HTM\", false).is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":57,"symbol":"IncrementalIgnore","kind":"type","lang":"rust","doc":"let matcher = &mut matchers[0]; if matcher.matched(\"src/generated.rs\", false).is_ignore() { println!(\"ignored\"); } ```","code":"pub struct IncrementalIgnore {\n /// The root exactly as it was given to `WalkBuilder`.\n root: PathBuf,\n /// The normalized root used only by the opt-in normalization routine.\n normalized_root: OnceLock>,\n /// The matcher for the configured root directory, loaded on first use.\n ignore: RootIgnore,\n /// Directory paths relative to `root`, excluding the root itself.\n dirs: HashMap,\n /// Options for additional filtering beyond gitignore.\n options: IncrementalIgnoreOptions,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":73,"symbol":"IncrementalIgnoreOptions","kind":"type","lang":"rust","doc":"The options for a matcher, mostly meant to duplicate as much as we can from `WalkParallel`.","code":"pub(crate) struct IncrementalIgnoreOptions {\n pub(crate) min_depth: Option,\n pub(crate) max_depth: Option,\n pub(crate) max_filesize: Option,\n pub(crate) hidden: bool,\n pub(crate) follow_links: bool,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":82,"symbol":"RootIgnore","kind":"type","lang":"rust","code":"enum RootIgnore {\n Unloaded(Ignore),\n Loaded(Ignore),\n NotDirectory,\n Stdin,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":94,"symbol":"CachedDir","kind":"type","lang":"rust","doc":"Cached traversal state for a directory relative to the configured root. The presence of an entry means that the directory and every ancestor between it and the root have already been checked.","code":"enum CachedDir {\n /// The directory may be descended into. The matcher includes the ignore\n /// rules loaded through this directory and is therefore the matcher to use\n /// for its children.\n Allowed(Ignore),\n /// The directory may not be descended into because it was ignored by a\n /// path rule or hidden-file filtering. Every descendant is consequently\n /// ignored, and ignore files inside this directory are not loaded.\n Ignored,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":106,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(\n root: PathBuf,\n ignore: Ignore,\n options: IncrementalIgnoreOptions,\n ) -> IncrementalIgnore {\n // File traversal special cases `-` to search stdin, so we recognize\n // it here for completeness too. In particular, we really want\n // `WalkBuilder::build_matchers` to return a matcher for every root,\n // even when it's a simple file (handled automatically) or when it's\n // stdin (necessarily special cased).\n //\n // If callers need to search a file or directory named `-`, then they\n // can use `./-`. As is the case for file traversal too.\n let ignore = if root == Path::new(\"-\") {\n RootIgnore::Stdin\n } else {\n RootIgnore::Unloaded(ignore)\n };\n IncrementalIgnore {\n root,\n normalized_root: OnceLock::new(),\n ignore,\n dirs: HashMap::new(),\n options,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":134,"symbol":"root","kind":"function","lang":"rust","doc":"Return the root that paths matched by this matcher are relative to.","code":"pub fn root(&self) -> &Path {\n &self.root\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":155,"symbol":"normalize","kind":"function","lang":"rust","doc":"Note also that this may reject paths that only differ in casing. For example, if the root path for this matcher is `/FOO` but the provided path is `/foo/bar`, then this may return `None`. Callers must ensure casing is consistent between the path provided and the root path for this matcher.","code":"pub fn normalize>(&self, path: P) -> Option {\n if matches!(self.ignore, RootIgnore::Stdin) {\n return None;\n }\n let path = normalize_absolute(path.as_ref())?;\n let root = self\n .normalized_root\n .get_or_init(|| normalize_absolute(&self.root))\n .as_ref()?;\n path.strip_prefix(root).ok().map(Path::to_path_buf)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":194,"symbol":"matched","kind":"function","lang":"rust","doc":"traversal on the root of this matcher may provide relative paths to this routine *without* calling [`IncrementalIgnore::normalize`]. The empty path represents the explicitly configured root and also returns non-match, consistent with recursive traversal where a root is always treated as being at depth zero.","code":"pub fn matched>(\n &mut self,\n path: P,\n is_dir: bool,\n ) -> IncrementalMatch {\n let (matched, err) = self.matched_with_errors(path, is_dir);\n if let Some(err) = err {\n log::debug!(\"error while loading ignore files: {err}\");\n }\n matched\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":213,"symbol":"matched_with_errors","kind":"function","lang":"rust","doc":"ignore files. This is equivalent to [`IncrementalIgnore::matched`], except that it returns any errors from newly loaded ignore files. Loading can partially succeed, so valid rules are always applied to the returned match even when an error is present.","code":"pub fn matched_with_errors>(\n &mut self,\n path: P,\n is_dir: bool,\n ) -> (IncrementalMatch, Option) {\n let mut errs = PartialErrorBuilder::default();\n let matched =\n self.matched_with_errors_impl(path.as_ref(), is_dir, &mut errs);\n (matched, errs.into_error_option())\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":224,"symbol":"matched_with_errors_impl","kind":"function","lang":"rust","code":"fn matched_with_errors_impl(\n &mut self,\n relative: &Path,\n is_dir: bool,\n errs: &mut PartialErrorBuilder,\n ) -> IncrementalMatch {\n // We short-circuit here when our matcher corresponds to `Stdin` in\n // order to always return a non-match. This is somewhat redundant with\n // `root_ignore()` which does this too, but we do it here so that it\n // always happens, e.g., before depth filtering.\n if relative.is_absolute() || matches!(self.ignore, RootIgnore::Stdin) {\n return IncrementalMatch::none(is_dir);\n }\n\n let (mut satisfies_min, mut edge_max) = (true, false);\n if self.options.min_depth.is_some() || self.options.max_depth.is_some()\n {\n let depth = relative\n .components()\n .filter_map(|component| match component {\n std::path::Component::CurDir => None,\n component => Some(component),\n })\n .count();\n satisfies_min =\n self.options.min_depth.is_none_or(|min| depth >= min);\n let satisfies_max =\n self.options.max_depth.is_none_o"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":310,"symbol":"matched_with_errors_ignore","kind":"function","lang":"rust","code":"fn matched_with_errors_ignore(\n &mut self,\n relative: &Path,\n is_dir: bool,\n errs: &mut PartialErrorBuilder,\n ) -> Option {\n let mut components = relative\n .components()\n .filter_map(|component| match component {\n std::path::Component::CurDir => None,\n component => Some(component),\n })\n .peekable();\n components.peek()?;\n\n // If the exact parent is cached, then all of its ancestors have\n // already been checked. An allowed cache entry is the matcher to use\n // for children of that directory, while an ignored cache entry is\n // terminal for every descendant. In the usual case, this avoids both\n // walking every component and allocating a relative directory path.\n //\n // Only try the fast path when the final component is a normal path\n // component. Invalid paths are handled by the component walk below.\n let has_normal_final_component =\n relative.components().next_back().is_some_and(|component| {\n matches!(component, std::path::Component::Normal(_))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":393,"symbol":"match_path","kind":"function","lang":"rust","code":"fn match_path(\n &self,\n ignore: &Ignore,\n relative: &Path,\n is_dir: bool,\n ) -> IncrementalMatch {\n let path = self.root.join(relative);\n let mut mat = IncrementalMatch::from_match(\n ignore.matched(&path, is_dir).map(|_| ()),\n is_dir,\n );\n // Whether a file is hidden or not has low precedence in filtering. We\n // only check it if we haven't matched anything above. This permits\n // callers to whitelist hidden files or directories.\n if self.options.hidden && mat.is_none() && is_hidden_path(&path) {\n mat = IncrementalMatch::ignore();\n }\n mat\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":413,"symbol":"root_ignore","kind":"function","lang":"rust","code":"fn root_ignore(\n &mut self,\n errs: &mut PartialErrorBuilder,\n ) -> Option {\n let ignore = match self.ignore {\n RootIgnore::Unloaded(ref ignore) => ignore.clone(),\n RootIgnore::Loaded(ref ignore) => return Some(ignore.clone()),\n RootIgnore::NotDirectory | RootIgnore::Stdin => return None,\n };\n if !self.root.is_dir() {\n self.ignore = RootIgnore::NotDirectory;\n return None;\n }\n\n let (parents, err) = ignore.add_parents(&self.root);\n errs.maybe_push(err);\n let (root, err) = parents.add_child(&self.root);\n errs.maybe_push(err);\n self.ignore = RootIgnore::Loaded(root.clone());\n Some(root)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":449,"symbol":"IncrementalMatch","kind":"type","lang":"rust","doc":"Generally speaking, callers that only care about specific files can stick to the `is_none()`, `is_ignore()` or `is_whitelist()` predicates. Directory entries are more complicated because we sometimes want to yield directories to descend into, but not actually visit (e.g., for the minimum depth filter). Or, we may want to yield a directory to visit but not descend into (e.g., for the maximum depth filter).","code":"pub struct IncrementalMatch {\n mat: Match<()>,\n should_descend: bool,\n is_within_depth: bool,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":456,"symbol":"none","kind":"function","lang":"rust","code":"fn none(is_dir: bool) -> IncrementalMatch {\n IncrementalMatch {\n mat: Match::None,\n should_descend: is_dir,\n is_within_depth: true,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":464,"symbol":"ignore","kind":"function","lang":"rust","code":"fn ignore() -> IncrementalMatch {\n IncrementalMatch {\n mat: Match::Ignore(()),\n should_descend: false,\n is_within_depth: true,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":472,"symbol":"from_match","kind":"function","lang":"rust","code":"fn from_match(mat: Match<()>, is_dir: bool) -> IncrementalMatch {\n let should_descend = is_dir && !mat.is_ignore();\n IncrementalMatch { mat, should_descend, is_within_depth: true }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":477,"symbol":"no_descent","kind":"function","lang":"rust","code":"fn no_descent(self) -> IncrementalMatch {\n IncrementalMatch { should_descend: false, ..self }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":481,"symbol":"not_within_depth","kind":"function","lang":"rust","code":"fn not_within_depth(self) -> IncrementalMatch {\n IncrementalMatch { is_within_depth: false, ..self }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":486,"symbol":"is_none","kind":"function","lang":"rust","doc":"Returns true if the match result didn't match anything.","code":"pub fn is_none(&self) -> bool {\n self.mat.is_none()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":491,"symbol":"is_ignore","kind":"function","lang":"rust","doc":"Returns true if the match result implies the path should be ignored.","code":"pub fn is_ignore(&self) -> bool {\n self.mat.is_ignore()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":497,"symbol":"is_whitelist","kind":"function","lang":"rust","doc":"Returns true if the match result implies the path should be whitelisted.","code":"pub fn is_whitelist(&self) -> bool {\n self.mat.is_whitelist()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":513,"symbol":"should_descend","kind":"function","lang":"rust","doc":"[`IncrementalMatch::should_descend`]. This can occur, for example, when a maximum depth setting allows a directory through, but where none of its children entries should be visited. This is always `false` for a file path that does *not* correspond to a directory.","code":"pub fn should_descend(&self) -> bool {\n self.should_descend\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":526,"symbol":"is_within_depth","kind":"function","lang":"rust","doc":"This is `false` when a path corresponds to a directory and is less than the minimum depth. In this case, callers should continue looking inside that directory. This is always `true` for a match corresponding to a file path that isn't a directory.","code":"pub fn is_within_depth(&self) -> bool {\n self.is_within_depth\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":532,"symbol":"invert","kind":"function","lang":"rust","doc":"Inverts the match so that `Ignore` becomes `Whitelist` and `Whitelist` becomes `Ignore`. A non-match remains the same.","code":"pub fn invert(self) -> IncrementalMatch {\n IncrementalMatch { mat: self.mat.invert(), ..self }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":542,"symbol":"normalize_absolute","kind":"function","lang":"rust","doc":"Return a lexically normalized absolute representation of `path`. This collapses `.` and `..`, but intentionally does not canonicalize or resolve symlinks. Ignore rules apply to the lexical path, and resolving a symlink below a root could move the result outside of that root.","code":"fn normalize_absolute(path: &Path) -> Option {\n let absolute = std::path::absolute(path).ok()?;\n let mut normalized = PathBuf::new();\n for component in absolute.components() {\n match component {\n std::path::Component::CurDir => {}\n std::path::Component::ParentDir => {\n normalized.pop();\n }\n _ => normalized.push(component.as_os_str()),\n }\n }\n Some(normalized)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":572,"symbol":"wfile","kind":"function","lang":"rust","code":"fn wfile>(path: P, contents: &str) {\n let mut file = File::create(path).unwrap();\n file.write_all(contents.as_bytes()).unwrap();\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":577,"symbol":"mkdirp","kind":"function","lang":"rust","code":"fn mkdirp>(path: P) {\n fs::create_dir_all(path).unwrap();\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":581,"symbol":"tmpdir","kind":"function","lang":"rust","code":"fn tmpdir() -> TempDir {\n TempDir::new().unwrap()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":585,"symbol":"builder","kind":"function","lang":"rust","code":"fn builder>(path: P) -> WalkBuilder {\n let mut builder = WalkBuilder::new(path);\n builder.git_global(false);\n builder\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":591,"symbol":"one_matcher","kind":"function","lang":"rust","code":"fn one_matcher(builder: &WalkBuilder) -> IncrementalIgnore {\n let mut matchers = builder.build_matchers();\n assert_eq!(matchers.len(), 1);\n matchers.pop().unwrap()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":597,"symbol":"builders","kind":"function","lang":"rust","code":"fn builders, P: AsRef>(\n paths: I,\n ) -> WalkBuilder {\n let mut builder = WalkBuilder::from_iter(paths);\n builder.git_global(false);\n builder\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":605,"symbol":"matchers","kind":"function","lang":"rust","code":"fn matchers(builder: &WalkBuilder) -> Vec {\n builder.build_matchers()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":609,"symbol":"matchedf","kind":"function","lang":"rust","code":"fn matchedf>(\n matcher: &mut IncrementalIgnore,\n path: P,\n ) -> IncrementalMatch {\n let (matched, err) = matcher.matched_with_errors(path, false);\n assert!(err.is_none(), \"unexpected matcher error: {err:?}\");\n matched\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":618,"symbol":"matchedd","kind":"function","lang":"rust","code":"fn matchedd>(\n matcher: &mut IncrementalIgnore,\n path: P,\n ) -> IncrementalMatch {\n let (matched, err) = matcher.matched_with_errors(path, true);\n assert!(err.is_none(), \"unexpected matcher error: {err:?}\");\n matched\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":629,"symbol":"nested_parent_gitignores","kind":"function","lang":"rust","doc":"Test that multiple parent ignore files, when nested, are respected.","code":"fn nested_parent_gitignores() {\n let td = tmpdir();\n let root = td.path().join(\"project/work\");\n mkdirp(td.path().join(\".git\"));\n mkdirp(root.join(\"src\"));\n wfile(td.path().join(\".gitignore\"), \"*.tmp\\n\");\n wfile(td.path().join(\"project/.gitignore\"), \"!keep.tmp\\nnested.log\\n\");\n\n let mut m = one_matcher(&builder(&root));\n assert_eq!(m.root(), root);\n assert!(matchedf(&mut m, \"src/drop.tmp\").is_ignore());\n assert!(matchedf(&mut m, \"src/keep.tmp\").is_whitelist());\n assert!(matchedf(&mut m, \"src/nested.log\").is_ignore());\n assert!(matchedf(&mut m, \"src/ok.rs\").is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":648,"symbol":"anchored_child_rule_uses_child_root","kind":"function","lang":"rust","doc":"Test that an anchored rule in a child directory is matched relative to that directory, not relative to the configured root.","code":"fn anchored_child_rule_uses_child_root() {\n let td = tmpdir();\n let root = td.path().join(\"root\");\n mkdirp(root.join(\"a\"));\n wfile(root.join(\"a/.ignore\"), \"/foo\\n\");\n\n let mut m = one_matcher(&builder(&root));\n assert!(matchedf(&mut m, \"a/foo\").is_ignore());\n assert!(matchedf(&mut m, \"a/b/foo\").is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":662,"symbol":"leading_dot_slash_impacts_matching","kind":"function","lang":"rust","doc":"Test that a leading `./` impacts how the rules are matched.","code":"fn leading_dot_slash_impacts_matching() {\n let td = tmpdir();\n let root = td.path().join(\"root\");\n mkdirp(root.join(\"a\"));\n wfile(root.join(\".ignore\"), \"/foo\\n\");\n wfile(root.join(\"a/.ignore\"), \"/foo\\n\");\n\n let mut m = one_matcher(&builder(&root));\n assert!(matchedf(&mut m, \"foo\").is_ignore());\n assert!(matchedf(&mut m, \"./foo\").is_none());\n assert!(matchedf(&mut m, \"a/allowed\").is_none());\n assert!(matchedf(&mut m, \"a/foo\").is_ignore());\n assert!(matchedf(&mut m, \"./a/foo\").is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":679,"symbol":"parent_ignore_and_custom_ignore","kind":"function","lang":"rust","doc":"Test that custom ignore files are respected.","code":"fn parent_ignore_and_custom_ignore() {\n let td = tmpdir();\n let root = td.path().join(\"project/work\");\n mkdirp(root.join(\"src\"));\n wfile(td.path().join(\".ignore\"), \"*.cache\\n\");\n wfile(td.path().join(\".rgignore\"), \"*.svg\\n\");\n wfile(td.path().join(\"project/.ignore\"), \"!keep.cache\\n\");\n wfile(td.path().join(\"project/.rgignore\"), \"!keep.svg\\n\");\n\n let mut builder = builder(&root);\n builder.add_custom_ignore_filename(\".rgignore\");\n let mut m = one_matcher(&builder);\n assert!(matchedf(&mut m, \"src/drop.cache\").is_ignore());\n assert!(matchedf(&mut m, \"src/keep.cache\").is_whitelist());\n assert!(matchedf(&mut m, \"src/drop.svg\").is_ignore());\n assert!(matchedf(&mut m, \"src/keep.svg\").is_whitelist());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":699,"symbol":"glob_overrides_are_applied","kind":"function","lang":"rust","doc":"Test that glob overrides take precedence over ignore files.","code":"fn glob_overrides_are_applied() {\n let td = tmpdir();\n wfile(td.path().join(\".ignore\"), \"keep.rs\\n!drop.rs\\n\");\n\n let mut overrides = OverrideBuilder::new(td.path());\n overrides.add(\"keep.rs\").unwrap();\n overrides.add(\"!drop.rs\").unwrap();\n let mut b = builder(td.path());\n b.overrides(overrides.build().unwrap());\n let mut m = one_matcher(&b);\n\n assert!(matchedf(&mut m, \"keep.rs\").is_whitelist());\n assert!(matchedf(&mut m, \"drop.rs\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":717,"symbol":"glob_overrides_apply_to_ancestors","kind":"function","lang":"rust","doc":"Test that an override-ignored directory prevents matching rules below it, just as it prevents a traversal from descending into the directory.","code":"fn glob_overrides_apply_to_ancestors() {\n let td = tmpdir();\n mkdirp(td.path().join(\"blocked\"));\n wfile(td.path().join(\"blocked/.ignore\"), \"!keep.rs\\n\");\n\n let mut overrides = OverrideBuilder::new(td.path());\n overrides.add(\"!blocked/\").unwrap();\n let mut b = builder(td.path());\n b.overrides(overrides.build().unwrap());\n let mut m = one_matcher(&b);\n\n assert!(matchedf(&mut m, \"blocked/keep.rs\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":734,"symbol":"file_types_are_applied","kind":"function","lang":"rust","doc":"Test that file type selections are applied to files, but not directories.","code":"fn file_types_are_applied() {\n let td = tmpdir();\n mkdirp(td.path().join(\"src\"));\n\n let mut types = TypesBuilder::new();\n types.add(\"rust\", \"*.rs\").unwrap();\n types.select(\"rust\");\n let mut b = builder(td.path());\n b.types(types.build().unwrap());\n let mut m = one_matcher(&b);\n\n assert!(matchedd(&mut m, \"src\").is_none());\n assert!(matchedf(&mut m, \"src/lib.rs\").is_whitelist());\n assert!(matchedf(&mut m, \"README.md\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":751,"symbol":"directly_ignored_directory_is_not_descended","kind":"function","lang":"rust","code":"fn directly_ignored_directory_is_not_descended() {\n let td = tmpdir();\n mkdirp(td.path().join(\".git\"));\n mkdirp(td.path().join(\"blocked\"));\n wfile(td.path().join(\".gitignore\"), \"blocked/\\n\");\n\n let mut m = one_matcher(&builder(td.path()));\n let dir = matchedd(&mut m, \"blocked\");\n assert!(dir.is_ignore());\n assert!(!dir.should_descend());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":767,"symbol":"ignored_ancestor_wins","kind":"function","lang":"rust","doc":"Test that when a directory is ignored, anything below it always ignored even when there are explicit whitelist rules. This matches directory traversal semantics.","code":"fn ignored_ancestor_wins() {\n let td = tmpdir();\n mkdirp(td.path().join(\".git\"));\n mkdirp(td.path().join(\"blocked\"));\n mkdirp(td.path().join(\"open\"));\n // This is the key line: since the entire `blocked` directory is\n // ignored, a proper file traversal won't ever descend into it. So\n // `blocked/keep.rs` should be ignored even if there are ignore rules\n // \"beneath\" it that whitelist it.\n wfile(td.path().join(\".gitignore\"), \"blocked/\\n!blocked/keep.rs\\n\");\n wfile(td.path().join(\"blocked/.gitignore\"), \"!keep.rs\\n\");\n\n let mut m = one_matcher(&builder(td.path()));\n assert!(matchedf(&mut m, \"blocked/keep.rs\").is_ignore());\n assert!(matchedf(&mut m, \"blocked/other.rs\").is_ignore());\n assert!(matchedf(&mut m, \"open/keep.rs\").is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":788,"symbol":"respects_git_repository_boundaries","kind":"function","lang":"rust","doc":"Test that we respect git boundaries. And that we don't respect git boundaries when not configured to do so.","code":"fn respects_git_repository_boundaries() {\n let td = tmpdir();\n let root = td.path().join(\"repo/src\");\n mkdirp(td.path().join(\"repo/.git\"));\n mkdirp(&root);\n wfile(td.path().join(\".gitignore\"), \"outside-rule\\n\");\n wfile(td.path().join(\".ignore\"), \"tool-rule\\n\");\n wfile(td.path().join(\"repo/.gitignore\"), \"inside-rule\\n\");\n\n let mut m = one_matcher(&builder(&root));\n assert!(matchedf(&mut m, \"inside-rule\").is_ignore());\n assert!(matchedf(&mut m, \"outside-rule\").is_none());\n assert!(matchedf(&mut m, \"tool-rule\").is_ignore());\n\n let mut no_git_required = builder(&root);\n no_git_required.require_git(false);\n let mut m = one_matcher(&no_git_required);\n assert!(matchedf(&mut m, \"outside-rule\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":811,"symbol":"compiled_matchers_are_reused","kind":"function","lang":"rust","doc":"Test that when a gitignore matcher in a parent directory is created, we reuse that matcher from memory even if it's changed on disk.","code":"fn compiled_matchers_are_reused() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a\"));\n wfile(td.path().join(\"a/.ignore\"), \"*.tmp\\n\");\n\n let mut m = one_matcher(&builder(td.path()));\n assert!(matchedf(&mut m, \"a/first.tmp\").is_ignore());\n\n // Below demonstrates that this new ignore file contents\n // aren't actually picked up because it was already loaded.\n wfile(td.path().join(\"a/.ignore\"), \"!*.tmp\\n*.rs\\n\");\n assert!(matchedf(&mut m, \"a/first.tmp\").is_ignore());\n assert!(matchedf(&mut m, \"a/second.tmp\").is_ignore());\n assert!(matchedf(&mut m, \"a/keep.rs\").is_none());\n // To get the new ignore file, we need to rebuild the matcher.\n let mut m = one_matcher(&builder(td.path()));\n assert!(matchedf(&mut m, \"a/first.tmp\").is_whitelist());\n assert!(matchedf(&mut m, \"a/second.tmp\").is_whitelist());\n assert!(matchedf(&mut m, \"a/keep.rs\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":833,"symbol":"cached_allowed_parent_matches_children","kind":"function","lang":"rust","code":"fn cached_allowed_parent_matches_children() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b\"));\n wfile(td.path().join(\"a/b/.ignore\"), \"ignored\\n\");\n\n let mut m = one_matcher(&builder(td.path()));\n assert!(matchedf(&mut m, \"a/b/allowed\").is_none());\n assert!(matches!(\n m.dirs.get(Path::new(\"a/b\")),\n Some(CachedDir::Allowed(_))\n ));\n assert!(matchedf(&mut m, \"a/b/ignored\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":848,"symbol":"cached_ignored_parent_matches_children","kind":"function","lang":"rust","code":"fn cached_ignored_parent_matches_children() {\n let td = tmpdir();\n mkdirp(td.path().join(\"blocked\"));\n wfile(td.path().join(\".ignore\"), \"blocked/\\n\");\n\n let mut m = one_matcher(&builder(td.path()));\n assert!(matchedf(&mut m, \"blocked/first\").is_ignore());\n assert!(matches!(\n m.dirs.get(Path::new(\"blocked\")),\n Some(CachedDir::Ignored)\n ));\n assert!(matchedf(&mut m, \"blocked/second\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":863,"symbol":"cached_parent_matcher_is_used_for_directory","kind":"function","lang":"rust","code":"fn cached_parent_matcher_is_used_for_directory() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b\"));\n wfile(td.path().join(\"a/b/.ignore\"), \"**\\n\");\n\n let mut m = one_matcher(&builder(td.path()));\n assert!(matchedf(&mut m, \"a/b/file\").is_ignore());\n assert!(matches!(\n m.dirs.get(Path::new(\"a/b\")),\n Some(CachedDir::Allowed(_))\n ));\n let dir = matchedd(&mut m, \"a/b\");\n assert!(dir.is_none());\n assert!(dir.should_descend());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":881,"symbol":"compiled_multi_matchers_are_reused","kind":"function","lang":"rust","doc":"Like `compiled_matchers_are_reused`, but with multiple roots.","code":"fn compiled_multi_matchers_are_reused() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c\"));\n\n wfile(td.path().join(\"a/.ignore\"), \"*.tmp\\n\");\n let mut mats = matchers(&builders([\n td.path().join(\"a/b\"),\n td.path().join(\"a/b/c\"),\n ]));\n assert!(matchedf(&mut mats[0], \"first.tmp\").is_ignore());\n assert!(matchedf(&mut mats[0], \"c/first.tmp\").is_ignore());\n\n // Even though we haven't used the second matcher, it should still\n // reuse the `a/.ignore` above. If it didn't, then `a/b/c/first.tmp`\n // below would be whitelisted.\n wfile(td.path().join(\"a/.ignore\"), \"!*.tmp\\n\");\n assert!(matchedf(&mut mats[1], \"first.tmp\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":901,"symbol":"compiled_multi_child_matchers_are_not_reused","kind":"function","lang":"rust","code":"fn compiled_multi_child_matchers_are_not_reused() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c/d/e\"));\n\n wfile(td.path().join(\"a/b/c/d/e/.ignore\"), \"*.tmp\\n\");\n let mut mats = matchers(&builders([\n td.path().join(\"a/b\"),\n td.path().join(\"a/b/c\"),\n ]));\n // Some sanity checking first.\n assert!(matchedf(&mut mats[0], \"c/first.tmp\").is_none());\n assert!(matchedf(&mut mats[0], \"c/d/first.tmp\").is_none());\n assert!(matchedf(&mut mats[0], \"c/d/e/first.tmp\").is_ignore());\n\n // Now write a new ignore file at the same location as above\n // and check that the other matcher still uses the \"stale\" data.\n wfile(td.path().join(\"a/b/c/d/e/.ignore\"), \"!*.tmp\\n\");\n assert!(matchedf(&mut mats[1], \"first.tmp\").is_none());\n assert!(matchedf(&mut mats[1], \"d/first.tmp\").is_none());\n // This is the punch line: because we didn't load `mats[1]` before\n // changing the ignore file, it loads it here and thus this path gets\n // whitelisted.\n assert!(matchedf(&mut mats[1], \"d/e/first.tmp\").is_whitelist());\n // ... but `mats[0]` still uses the stale g"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":941,"symbol":"partial_errors_keep_valid_rules","kind":"function","lang":"rust","doc":"Tests that even when there is an error with a glob pattern, we still respect other glob patterns that are valid.","code":"fn partial_errors_keep_valid_rules() {\n let td = tmpdir();\n let root = td.path().join(\"work\");\n mkdirp(&root);\n wfile(td.path().join(\".ignore\"), \"{bad\\n*.tmp\\n\");\n\n let mut builder = builder(&root);\n builder.git_ignore(false).git_exclude(false);\n let mut m = one_matcher(&builder);\n let (matched, err) = m.matched_with_errors(\"drop.tmp\", false);\n assert!(err.is_some());\n assert!(matched.is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":958,"symbol":"parent_loading_can_be_disabled","kind":"function","lang":"rust","doc":"Tests that parent rules are not respected if the matcher is configured not to do so.","code":"fn parent_loading_can_be_disabled() {\n let td = tmpdir();\n let root = td.path().join(\"work\");\n mkdirp(&root);\n wfile(td.path().join(\".ignore\"), \"parent-rule\\n\");\n wfile(root.join(\".ignore\"), \"root-rule\\n\");\n\n let mut b = builder(&root);\n b.parents(false);\n let mut m = one_matcher(&b);\n assert!(matchedf(&mut m, \"parent-rule\").is_none());\n assert!(matchedf(&mut m, \"root-rule\").is_ignore());\n\n // Sanity check that without `parents(false)`, the parent rule is\n // respected.\n let mut m = one_matcher(&builder(&root));\n assert!(matchedf(&mut m, \"parent-rule\").is_ignore());\n assert!(matchedf(&mut m, \"root-rule\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":981,"symbol":"paths_are_relative_to_the_root","kind":"function","lang":"rust","doc":"Tests that we can normalize a file path that isn't already in \"normal\" relative form, and then use that to match on ignore files.","code":"fn paths_are_relative_to_the_root() {\n let td = tmpdir();\n let root = td.path().join(\"root\");\n let outside = td.path().join(\"outside\");\n mkdirp(&root);\n mkdirp(&outside);\n wfile(root.join(\".ignore\"), \"file\\n\");\n\n let mut m = one_matcher(&builder(&root));\n assert!(matchedd(&mut m, \"\").is_none());\n assert!(matchedd(&mut m, \".\").is_none());\n assert!(matchedf(&mut m, \"file\").is_ignore());\n // Doesn't work because it isn't relative to the root. It's absolute.\n assert!(matchedf(&mut m, root.join(\"file\")).is_none());\n // Also doesn't work because while it's relative, it contains `..`.\n assert!(matchedf(&mut m, \"dir/../file\").is_none());\n\n let norm = m.normalize(root.join(\"dir/../file\")).unwrap();\n assert_eq!(norm, Path::new(\"file\"));\n assert!(matchedf(&mut m, \"file\").is_ignore());\n\n // Doesn't normalize because its an absolute path outside of our root.\n assert_eq!(m.normalize(outside.join(\"file\")), None);\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":1009,"symbol":"multiple_roots_keep_their_own_context","kind":"function","lang":"rust","doc":"Tests that two matchers in two different directories correctly interpret the same parent gitignore file.","code":"fn multiple_roots_keep_their_own_context() {\n let td = tmpdir();\n let root_a = td.path().join(\"a\");\n let root_b = td.path().join(\"b\");\n mkdirp(td.path().join(\".git\"));\n mkdirp(&root_a);\n mkdirp(&root_b);\n wfile(td.path().join(\".gitignore\"), \"/a/*.tmp\\n/b/*.log\\n\");\n\n let mut builder =\n builders([root_a.as_path(), Path::new(\"-\"), root_b.as_path()]);\n builder.git_global(false);\n let mut ms = matchers(&builder);\n assert_eq!(ms.len(), 3);\n assert_eq!(ms[0].root(), root_a);\n assert_eq!(ms[1].root(), Path::new(\"-\"));\n assert_eq!(ms[2].root(), root_b);\n assert!(matchedf(&mut ms[0], \"drop.tmp\").is_ignore());\n assert!(matchedf(&mut ms[0], \"keep.log\").is_none());\n assert!(matchedf(&mut ms[1], \"anything\").is_none());\n assert_eq!(ms[1].normalize(\"anything\"), None);\n assert!(matchedf(&mut ms[2], \"keep.tmp\").is_none());\n assert!(matchedf(&mut ms[2], \"drop.log\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":1036,"symbol":"dot_dash_root_is_not_stdin","kind":"function","lang":"rust","doc":"Tests that only the exact `-` root represents standard input.","code":"fn dot_dash_root_is_not_stdin() {\n let m = one_matcher(&builder(\"./-\"));\n assert_eq!(m.root(), Path::new(\"./-\"));\n assert_eq!(m.normalize(\"./-/file\"), Some(PathBuf::from(\"file\")));\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":1043,"symbol":"stdin_is_inert_with_depth_limits","kind":"function","lang":"rust","code":"fn stdin_is_inert_with_depth_limits() {\n let mut b = builder(\"-\");\n b.min_depth(Some(2));\n let mut m = one_matcher(&b);\n let mat = matchedf(&mut m, \"file\");\n assert!(mat.is_none());\n assert!(mat.is_within_depth());\n\n let mut b = builder(\"-\");\n b.max_depth(Some(0));\n let mut m = one_matcher(&b);\n let mat = matchedd(&mut m, \"dir\");\n assert!(mat.is_none());\n assert!(mat.is_within_depth());\n assert!(mat.should_descend());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":1064,"symbol":"symlink_path_stays_under_lexical_root","kind":"function","lang":"rust","doc":"Tests that ignore matching works lexically, and doesn't accidentally resolve symbolic links.","code":"fn symlink_path_stays_under_lexical_root() {\n use std::os::unix::fs::symlink;\n\n let td = tmpdir();\n let root = td.path().join(\"root\");\n let outside = td.path().join(\"outside\");\n mkdirp(&root);\n mkdirp(&outside);\n wfile(root.join(\".ignore\"), \"link\\n\");\n wfile(outside.join(\"target\"), \"\");\n symlink(outside.join(\"target\"), root.join(\"link\")).unwrap();\n\n let mut m = one_matcher(&builder(&root));\n assert!(matchedf(&mut m, \"link\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":1081,"symbol":"depth_limits","kind":"function","lang":"rust","code":"fn depth_limits() {\n let td = tmpdir();\n mkdirp(td.path().join(\"a/b/c/d\"));\n\n let mut b = builder(td.path());\n b.min_depth(Some(2)).max_depth(Some(3));\n let mut m = one_matcher(&b);\n\n let dir = matchedd(&mut m, \"a\");\n assert!(!dir.is_within_depth());\n assert!(dir.should_descend());\n assert!(matchedf(&mut m, \"file\").is_ignore());\n\n let dir = matchedd(&mut m, \"a/b\");\n assert!(dir.is_within_depth());\n assert!(dir.should_descend());\n assert!(!matchedf(&mut m, \"a/file\").is_ignore());\n\n let dir = matchedd(&mut m, \"a/b/c\");\n assert!(dir.is_within_depth());\n assert!(!dir.should_descend());\n assert!(!matchedf(&mut m, \"a/b/file\").is_ignore());\n assert!(matchedf(&mut m, \"a/b/c/file\").is_ignore());\n\n let dir = matchedd(&mut m, \"a/b/c/d\");\n assert!(dir.is_ignore());\n assert!(!dir.is_within_depth());\n assert!(!dir.should_descend());\n assert!(matchedf(&mut m, \"a/b/c/d/file\").is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/incremental.rs","line":1113,"symbol":"depth_limits_apply_to_root","kind":"function","lang":"rust","code":"fn depth_limits_apply_to_root() {\n let td = tmpdir();\n\n let mut b = builder(td.path());\n b.min_depth(Some(1));\n let mut m = one_matcher(&b);\n for path in [\"\", \".\"] {\n let root = matchedd(&mut m, path);\n assert!(root.is_none());\n assert!(!root.is_within_depth());\n assert!(root.should_descend());\n }\n\n let mut b = builder(td.path());\n b.max_depth(Some(0));\n let mut m = one_matcher(&b);\n for path in [\"\", \".\"] {\n let root = matchedd(&mut m, path);\n assert!(root.is_none());\n assert!(root.is_within_depth());\n assert!(!root.should_descend());\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":68,"symbol":"Error","kind":"type","lang":"rust","doc":"Represents an error that can occur when parsing a gitignore file.","code":"pub enum Error {\n /// A collection of \"soft\" errors. These occur when adding an ignore\n /// file partially succeeded.\n Partial(Vec),\n /// An error associated with a specific line number.\n WithLineNumber {\n /// The line number.\n line: u64,\n /// The underlying error.\n err: Box,\n },\n /// An error associated with a particular file path.\n WithPath {\n /// The file path.\n path: PathBuf,\n /// The underlying error.\n err: Box,\n },\n /// An error associated with a particular directory depth when recursively\n /// walking a directory.\n WithDepth {\n /// The directory depth.\n depth: usize,\n /// The underlying error.\n err: Box,\n },\n /// An error that occurs when a file loop is detected when traversing\n /// symbolic links.\n Loop {\n /// The ancestor file path in the loop.\n ancestor: PathBuf,\n /// The child file path in the loop.\n child: PathBuf,\n },\n /// An error that occurs when doing I/O, such as reading an ignore file.\n Io(std::io::Error),\n /// An error that occurs when trying to parse a glob.\n Glo"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":123,"symbol":"clone","kind":"function","lang":"rust","code":"fn clone(&self) -> Error {\n match *self {\n Error::Partial(ref errs) => Error::Partial(errs.clone()),\n Error::WithLineNumber { line, ref err } => {\n Error::WithLineNumber { line, err: err.clone() }\n }\n Error::WithPath { ref path, ref err } => {\n Error::WithPath { path: path.clone(), err: err.clone() }\n }\n Error::WithDepth { depth, ref err } => {\n Error::WithDepth { depth, err: err.clone() }\n }\n Error::Loop { ref ancestor, ref child } => Error::Loop {\n ancestor: ancestor.clone(),\n child: child.clone(),\n },\n Error::Io(ref err) => match err.raw_os_error() {\n Some(e) => Error::Io(std::io::Error::from_raw_os_error(e)),\n None => {\n Error::Io(std::io::Error::new(err.kind(), err.to_string()))\n }\n },\n Error::Glob { ref glob, ref err } => {\n Error::Glob { glob: glob.clone(), err: err.clone() }\n }\n Error::UnrecognizedFileType(ref err) => {\n Error::UnrecognizedFileType(e"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":162,"symbol":"is_partial","kind":"function","lang":"rust","doc":"Returns true if this is a partial error. A partial error occurs when only some operations failed while others may have succeeded. For example, an ignore file may contain an invalid glob among otherwise valid globs.","code":"pub fn is_partial(&self) -> bool {\n match *self {\n Error::Partial(_) => true,\n Error::WithLineNumber { ref err, .. } => err.is_partial(),\n Error::WithPath { ref err, .. } => err.is_partial(),\n Error::WithDepth { ref err, .. } => err.is_partial(),\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":173,"symbol":"is_io","kind":"function","lang":"rust","doc":"Returns true if this error is exclusively an I/O error.","code":"pub fn is_io(&self) -> bool {\n match *self {\n Error::Partial(ref errs) => errs.len() == 1 && errs[0].is_io(),\n Error::WithLineNumber { ref err, .. } => err.is_io(),\n Error::WithPath { ref err, .. } => err.is_io(),\n Error::WithDepth { ref err, .. } => err.is_io(),\n Error::Loop { .. } => false,\n Error::Io(_) => true,\n Error::Glob { .. } => false,\n Error::UnrecognizedFileType(_) => false,\n Error::InvalidDefinition => false,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":207,"symbol":"io_error","kind":"function","lang":"rust","doc":"[`None`]: https://doc.rust-lang.org/stable/std/option/enum.Option.html#variant.None [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html [`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html [`Error`]: struct.Error.html [`into_io_error`]: struct.Error.html#method.into_io_error [impl]: struct.Error.html#impl-From%3CError%3E","code":"pub fn io_error(&self) -> Option<&std::io::Error> {\n match *self {\n Error::Partial(ref errs) => {\n if errs.len() == 1 {\n errs[0].io_error()\n } else {\n None\n }\n }\n Error::WithLineNumber { ref err, .. } => err.io_error(),\n Error::WithPath { ref err, .. } => err.io_error(),\n Error::WithDepth { ref err, .. } => err.io_error(),\n Error::Loop { .. } => None,\n Error::Io(ref err) => Some(err),\n Error::Glob { .. } => None,\n Error::UnrecognizedFileType(_) => None,\n Error::InvalidDefinition => None,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":232,"symbol":"into_io_error","kind":"function","lang":"rust","doc":"Similar to [`io_error`] except consumes self to convert to the original [`std::io::Error`] if one exists. [`io_error`]: struct.Error.html#method.io_error [`std::io::Error`]: https://doc.rust-lang.org/stable/std/io/struct.Error.html","code":"pub fn into_io_error(self) -> Option {\n match self {\n Error::Partial(mut errs) => {\n if errs.len() == 1 {\n errs.remove(0).into_io_error()\n } else {\n None\n }\n }\n Error::WithLineNumber { err, .. } => err.into_io_error(),\n Error::WithPath { err, .. } => err.into_io_error(),\n Error::WithDepth { err, .. } => err.into_io_error(),\n Error::Loop { .. } => None,\n Error::Io(err) => Some(err),\n Error::Glob { .. } => None,\n Error::UnrecognizedFileType(_) => None,\n Error::InvalidDefinition => None,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":254,"symbol":"depth","kind":"function","lang":"rust","doc":"Returns a depth associated with recursively walking a directory (if this error was generated from a recursive directory iterator).","code":"pub fn depth(&self) -> Option {\n match *self {\n Error::WithPath { ref err, .. } => err.depth(),\n Error::WithDepth { depth, .. } => Some(depth),\n _ => None,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":263,"symbol":"with_path","kind":"function","lang":"rust","doc":"Turn an error into a tagged error with the given file path.","code":"fn with_path>(self, path: P) -> Error {\n Error::WithPath {\n path: path.as_ref().to_path_buf(),\n err: Box::new(self),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":271,"symbol":"with_depth","kind":"function","lang":"rust","doc":"Turn an error into a tagged error with the given depth.","code":"fn with_depth(self, depth: usize) -> Error {\n Error::WithDepth { depth, err: Box::new(self) }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":277,"symbol":"tagged","kind":"function","lang":"rust","doc":"Turn an error into a tagged error with the given file path and line number. If path is empty, then it is omitted from the error.","code":"fn tagged>(self, path: P, lineno: u64) -> Error {\n let errline =\n Error::WithLineNumber { line: lineno, err: Box::new(self) };\n if path.as_ref().as_os_str().is_empty() {\n return errline;\n }\n errline.with_path(path)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":287,"symbol":"from_walkdir","kind":"function","lang":"rust","doc":"Build an error from a walkdir error.","code":"fn from_walkdir(err: walkdir::Error) -> Error {\n let depth = err.depth();\n if let (Some(anc), Some(child)) = (err.loop_ancestor(), err.path()) {\n return Error::WithDepth {\n depth,\n err: Box::new(Error::Loop {\n ancestor: anc.to_path_buf(),\n child: child.to_path_buf(),\n }),\n };\n }\n let path = err.path().map(|p| p.to_path_buf());\n let mut ig_err = Error::WithDepth {\n depth,\n err: Box::new(Error::Io(std::io::Error::from(err))),\n };\n if let Some(path) = path {\n ig_err = Error::WithPath { path, err: Box::new(ig_err) };\n }\n ig_err\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":312,"symbol":"description","kind":"function","lang":"rust","code":"fn description(&self) -> &str {\n match *self {\n Error::Partial(_) => \"partial error\",\n Error::WithLineNumber { ref err, .. } => err.description(),\n Error::WithPath { ref err, .. } => err.description(),\n Error::WithDepth { ref err, .. } => err.description(),\n Error::Loop { .. } => \"file system loop found\",\n Error::Io(ref err) => err.description(),\n Error::Glob { ref err, .. } => err,\n Error::UnrecognizedFileType(_) => \"unrecognized file type\",\n Error::InvalidDefinition => \"invalid definition\",\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":328,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match *self {\n Error::Partial(ref errs) => {\n let msgs: Vec =\n errs.iter().map(|err| err.to_string()).collect();\n write!(f, \"{}\", msgs.join(\"\\n\"))\n }\n Error::WithLineNumber { line, ref err } => {\n write!(f, \"line {}: {}\", line, err)\n }\n Error::WithPath { ref path, ref err } => {\n write!(f, \"{}: {}\", path.display(), err)\n }\n Error::WithDepth { ref err, .. } => err.fmt(f),\n Error::Loop { ref ancestor, ref child } => write!(\n f,\n \"File system loop found: \\\n {} points to an ancestor {}\",\n child.display(),\n ancestor.display()\n ),\n Error::Io(ref err) => err.fmt(f),\n Error::Glob { glob: None, ref err } => write!(f, \"{}\", err),\n Error::Glob { glob: Some(ref glob), ref err } => {\n write!(f, \"error parsing glob '{}': {}\", glob, err)\n }\n Error::UnrecognizedFileType(ref ty) => {\n "} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":367,"symbol":"from","kind":"function","lang":"rust","code":"fn from(err: std::io::Error) -> Error {\n Error::Io(err)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":373,"symbol":"PartialErrorBuilder","kind":"type","lang":"rust","code":"struct PartialErrorBuilder(Vec);"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":376,"symbol":"push","kind":"function","lang":"rust","code":"fn push(&mut self, err: Error) {\n self.0.push(err);\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":380,"symbol":"push_ignore_io","kind":"function","lang":"rust","code":"fn push_ignore_io(&mut self, err: Error) {\n if !err.is_io() {\n self.push(err);\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":386,"symbol":"maybe_push","kind":"function","lang":"rust","code":"fn maybe_push(&mut self, err: Option) {\n if let Some(err) = err {\n self.push(err);\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":392,"symbol":"maybe_push_ignore_io","kind":"function","lang":"rust","code":"fn maybe_push_ignore_io(&mut self, err: Option) {\n if let Some(err) = err {\n self.push_ignore_io(err);\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":398,"symbol":"into_error_option","kind":"function","lang":"rust","code":"fn into_error_option(mut self) -> Option {\n if self.0.is_empty() {\n None\n } else if self.0.len() == 1 {\n Some(self.0.pop().unwrap())\n } else {\n Some(Error::Partial(self.0))\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":416,"symbol":"Match","kind":"type","lang":"rust","doc":"The result of a glob match. The type parameter `T` typically refers to a type that provides more information about a particular match. For example, it might identify the specific gitignore file and the specific glob pattern that caused the match.","code":"pub enum Match {\n /// The path didn't match any glob.\n None,\n /// The highest precedent glob matched indicates the path should be\n /// ignored.\n Ignore(T),\n /// The highest precedent glob matched indicates the path should be\n /// whitelisted.\n Whitelist(T),\n}"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":429,"symbol":"is_none","kind":"function","lang":"rust","doc":"Returns true if the match result didn't match any globs.","code":"pub fn is_none(&self) -> bool {\n match *self {\n Match::None => true,\n Match::Ignore(_) | Match::Whitelist(_) => false,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":437,"symbol":"is_ignore","kind":"function","lang":"rust","doc":"Returns true if the match result implies the path should be ignored.","code":"pub fn is_ignore(&self) -> bool {\n match *self {\n Match::Ignore(_) => true,\n Match::None | Match::Whitelist(_) => false,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":446,"symbol":"is_whitelist","kind":"function","lang":"rust","doc":"Returns true if the match result implies the path should be whitelisted.","code":"pub fn is_whitelist(&self) -> bool {\n match *self {\n Match::Whitelist(_) => true,\n Match::None | Match::Ignore(_) => false,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":455,"symbol":"invert","kind":"function","lang":"rust","doc":"Inverts the match so that `Ignore` becomes `Whitelist` and `Whitelist` becomes `Ignore`. A non-match remains the same.","code":"pub fn invert(self) -> Match {\n match self {\n Match::None => Match::None,\n Match::Ignore(t) => Match::Whitelist(t),\n Match::Whitelist(t) => Match::Ignore(t),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":464,"symbol":"inner","kind":"function","lang":"rust","doc":"Return the value inside this match if it exists.","code":"pub fn inner(&self) -> Option<&T> {\n match *self {\n Match::None => None,\n Match::Ignore(ref t) => Some(t),\n Match::Whitelist(ref t) => Some(t),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":475,"symbol":"map","kind":"function","lang":"rust","doc":"Apply the given function to the value inside this match. If the match has no value, then return the match unchanged.","code":"pub fn map U>(self, f: F) -> Match {\n match self {\n Match::None => Match::None,\n Match::Ignore(t) => Match::Ignore(f(t)),\n Match::Whitelist(t) => Match::Whitelist(f(t)),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":484,"symbol":"or","kind":"function","lang":"rust","doc":"Return the match if it is not none. Otherwise, return other.","code":"pub fn or(self, other: Self) -> Self {\n if self.is_none() { other } else { self }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":512,"symbol":"TempDir","kind":"type","lang":"rust","doc":"A simple wrapper for creating a temporary directory that is automatically deleted when it's dropped. We use this in lieu of tempfile because tempfile brings in too many dependencies.","code":"pub struct TempDir(PathBuf);"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":515,"symbol":"drop","kind":"function","lang":"rust","code":"fn drop(&mut self) {\n fs::remove_dir_all(&self.0).unwrap();\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":523,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new empty temporary directory under the system's configured temporary directory.","code":"pub fn new() -> Result {\n use std::sync::atomic::{AtomicUsize, Ordering};\n\n static TRIES: usize = 100;\n static COUNTER: AtomicUsize = AtomicUsize::new(0);\n\n let tmpdir = env::temp_dir();\n for _ in 0..TRIES {\n let count = COUNTER.fetch_add(1, Ordering::Relaxed);\n let path = tmpdir.join(\"rust-ignore\").join(count.to_string());\n if path.is_dir() {\n continue;\n }\n fs::create_dir_all(&path).map_err(|e| {\n err!(\"failed to create {}: {}\", path.display(), e)\n })?;\n return Ok(TempDir(path));\n }\n Err(err!(\"failed to create temp dir after {} tries\", TRIES))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/lib.rs","line":545,"symbol":"path","kind":"function","lang":"rust","doc":"Return the underlying path to this temporary directory.","code":"pub fn path(&self) -> &Path {\n &self.0\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":28,"symbol":"Glob","kind":"type","lang":"rust","doc":"Note that not all matches necessarily correspond to a specific glob. For example, if there are one or more whitelist globs and a file path doesn't match any glob in the set, then the file path is considered to be ignored. The lifetime `'a` refers to the lifetime of the matcher that produced this glob.","code":"pub struct Glob<'a>(GlobInner<'a>);"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":32,"symbol":"GlobInner","kind":"type","lang":"rust","code":"enum GlobInner<'a> {\n /// No glob matched, but the file path should still be ignored.\n UnmatchedIgnore,\n /// A glob matched.\n Matched(&'a gitignore::Glob),\n}"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":40,"symbol":"unmatched","kind":"function","lang":"rust","code":"fn unmatched() -> Glob<'a> {\n Glob(GlobInner::UnmatchedIgnore)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":47,"symbol":"Override","kind":"type","lang":"rust","doc":"Manages a set of overrides provided explicitly by the end user.","code":"pub struct Override(Gitignore);"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":51,"symbol":"empty","kind":"function","lang":"rust","doc":"Returns an empty matcher that never matches any file path.","code":"pub fn empty() -> Override {\n Override(Gitignore::empty())\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":58,"symbol":"path","kind":"function","lang":"rust","doc":"Returns the directory of this override set. All matches are done relative to this path.","code":"pub fn path(&self) -> &Path {\n self.0.path()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":65,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if and only if this matcher is empty. When a matcher is empty, it will never match any file path.","code":"pub fn is_empty(&self) -> bool {\n self.0.is_empty()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":70,"symbol":"num_ignores","kind":"function","lang":"rust","doc":"Returns the total number of ignore globs.","code":"pub fn num_ignores(&self) -> u64 {\n self.0.num_whitelists()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":75,"symbol":"num_whitelists","kind":"function","lang":"rust","doc":"Returns the total number of whitelisted globs.","code":"pub fn num_whitelists(&self) -> u64 {\n self.0.num_ignores()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":97,"symbol":"matched","kind":"function","lang":"rust","doc":"The given path is matched to the globs relative to the path given when building the override matcher. Specifically, before matching `path`, its prefix (as determined by a common suffix of the directory given) is stripped. If there is no common suffix/prefix overlap, then `path` is assumed to reside in the same directory as the root path for this set of overrides.","code":"pub fn matched<'a, P: AsRef>(\n &'a self,\n path: P,\n is_dir: bool,\n ) -> Match> {\n if self.is_empty() {\n return Match::None;\n }\n let mat = self.0.matched(path, is_dir).invert();\n if mat.is_none() && self.num_whitelists() > 0 && !is_dir {\n return Match::Ignore(Glob::unmatched());\n }\n mat.map(move |giglob| Glob(GlobInner::Matched(giglob)))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":115,"symbol":"OverrideBuilder","kind":"type","lang":"rust","doc":"Builds a matcher for a set of glob overrides.","code":"pub struct OverrideBuilder {\n builder: GitignoreBuilder,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":123,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new override builder. Matching is done relative to the directory path provided.","code":"pub fn new>(path: P) -> OverrideBuilder {\n let mut builder = GitignoreBuilder::new(path);\n builder.allow_unclosed_class(false);\n OverrideBuilder { builder }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":132,"symbol":"build","kind":"function","lang":"rust","doc":"Builds a new override matcher from the globs added so far. Once a matcher is built, no new globs can be added to it.","code":"pub fn build(&self) -> Result {\n Ok(Override(self.builder.build()?))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":142,"symbol":"add","kind":"function","lang":"rust","doc":"Add a glob to the set of overrides. Globs provided here have precisely the same semantics as a single line in a `gitignore` file, where the meaning of `!` is inverted: namely, `!` at the beginning of a glob will ignore a file. Without `!`, all matches of the glob provided are treated as whitelist matches.","code":"pub fn add(&mut self, glob: &str) -> Result<&mut OverrideBuilder, Error> {\n self.builder.add_line(None, glob)?;\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":153,"symbol":"case_insensitive","kind":"function","lang":"rust","doc":"Toggle whether the globs should be matched case insensitively or not. When this option is changed, only globs added after the change will be affected. This is disabled by default.","code":"pub fn case_insensitive(\n &mut self,\n yes: bool,\n ) -> Result<&mut OverrideBuilder, Error> {\n // TODO: This should not return a `Result`. Fix this in the next semver\n // release.\n self.builder.case_insensitive(yes)?;\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":180,"symbol":"allow_unclosed_class","kind":"function","lang":"rust","doc":"This default is different from the default for [`Gitignore`]. Namely, [`Gitignore`] is intended to match git's behavior as-is. But this abstraction for \"override\" globs does not necessarily conform to any other known specification and instead prioritizes better error messages.","code":"pub fn allow_unclosed_class(&mut self, yes: bool) -> &mut OverrideBuilder {\n self.builder.allow_unclosed_class(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":192,"symbol":"ov","kind":"function","lang":"rust","code":"fn ov(globs: &[&str]) -> Override {\n let mut builder = OverrideBuilder::new(ROOT);\n for glob in globs {\n builder.add(glob).unwrap();\n }\n builder.build().unwrap()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":201,"symbol":"empty","kind":"function","lang":"rust","code":"fn empty() {\n let ov = ov(&[]);\n assert!(ov.matched(\"a.foo\", false).is_none());\n assert!(ov.matched(\"a\", false).is_none());\n assert!(ov.matched(\"\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":209,"symbol":"simple","kind":"function","lang":"rust","code":"fn simple() {\n let ov = ov(&[\"*.foo\", \"!*.bar\"]);\n assert!(ov.matched(\"a.foo\", false).is_whitelist());\n assert!(ov.matched(\"a.foo\", true).is_whitelist());\n assert!(ov.matched(\"a.rs\", false).is_ignore());\n assert!(ov.matched(\"a.rs\", true).is_none());\n assert!(ov.matched(\"a.bar\", false).is_ignore());\n assert!(ov.matched(\"a.bar\", true).is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":220,"symbol":"only_ignores","kind":"function","lang":"rust","code":"fn only_ignores() {\n let ov = ov(&[\"!*.bar\"]);\n assert!(ov.matched(\"a.rs\", false).is_none());\n assert!(ov.matched(\"a.rs\", true).is_none());\n assert!(ov.matched(\"a.bar\", false).is_ignore());\n assert!(ov.matched(\"a.bar\", true).is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":229,"symbol":"precedence","kind":"function","lang":"rust","code":"fn precedence() {\n let ov = ov(&[\"*.foo\", \"!*.bar.foo\"]);\n assert!(ov.matched(\"a.foo\", false).is_whitelist());\n assert!(ov.matched(\"a.baz\", false).is_ignore());\n assert!(ov.matched(\"a.bar.foo\", false).is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":237,"symbol":"gitignore","kind":"function","lang":"rust","code":"fn gitignore() {\n let ov = ov(&[\"/foo\", \"bar/*.rs\", \"baz/**\"]);\n assert!(ov.matched(\"bar/lib.rs\", false).is_whitelist());\n assert!(ov.matched(\"bar/wat/lib.rs\", false).is_ignore());\n assert!(ov.matched(\"wat/bar/lib.rs\", false).is_ignore());\n assert!(ov.matched(\"foo\", false).is_whitelist());\n assert!(ov.matched(\"wat/foo\", false).is_ignore());\n assert!(ov.matched(\"baz\", false).is_ignore());\n assert!(ov.matched(\"baz/a\", false).is_whitelist());\n assert!(ov.matched(\"baz/a/b\", false).is_whitelist());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":250,"symbol":"allow_directories","kind":"function","lang":"rust","code":"fn allow_directories() {\n // This tests that directories are NOT ignored when they are unmatched.\n let ov = ov(&[\"*.rs\"]);\n assert!(ov.matched(\"foo.rs\", false).is_whitelist());\n assert!(ov.matched(\"foo.c\", false).is_ignore());\n assert!(ov.matched(\"foo\", false).is_ignore());\n assert!(ov.matched(\"foo\", true).is_none());\n assert!(ov.matched(\"src/foo.rs\", false).is_whitelist());\n assert!(ov.matched(\"src/foo.c\", false).is_ignore());\n assert!(ov.matched(\"src/foo\", false).is_ignore());\n assert!(ov.matched(\"src/foo\", true).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":264,"symbol":"absolute_path","kind":"function","lang":"rust","code":"fn absolute_path() {\n let ov = ov(&[\"!/bar\"]);\n assert!(ov.matched(\"./foo/bar\", false).is_none());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":270,"symbol":"case_insensitive","kind":"function","lang":"rust","code":"fn case_insensitive() {\n let ov = OverrideBuilder::new(ROOT)\n .case_insensitive(true)\n .unwrap()\n .add(\"*.html\")\n .unwrap()\n .build()\n .unwrap();\n assert!(ov.matched(\"foo.html\", false).is_whitelist());\n assert!(ov.matched(\"foo.HTML\", false).is_whitelist());\n assert!(ov.matched(\"foo.htm\", false).is_ignore());\n assert!(ov.matched(\"foo.HTM\", false).is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/overrides.rs","line":285,"symbol":"default_case_sensitive","kind":"function","lang":"rust","code":"fn default_case_sensitive() {\n let ov =\n OverrideBuilder::new(ROOT).add(\"*.html\").unwrap().build().unwrap();\n assert!(ov.matched(\"foo.html\", false).is_whitelist());\n assert!(ov.matched(\"foo.HTML\", false).is_ignore());\n assert!(ov.matched(\"foo.htm\", false).is_ignore());\n assert!(ov.matched(\"foo.HTM\", false).is_ignore());\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":19,"symbol":"is_hidden_path","kind":"function","lang":"rust","doc":"* The base name of the path starts with a `.`. * The file attributes have the `HIDDEN` property set. ## All other platforms This only returns true if the base name of the path starts with a `.`.","code":"pub(crate) fn is_hidden_path(dent: &Path) -> bool {\n #[cfg(not(windows))]\n fn imp(path: &Path) -> bool {\n is_hidden_path_only(path)\n }\n\n #[cfg(windows)]\n fn imp(path: &Path) -> bool {\n use std::os::windows::fs::MetadataExt;\n use winapi_util::file;\n\n if let Ok(md) = path.metadata() {\n if file::is_hidden(md.file_attributes() as u64) {\n return true;\n }\n }\n is_hidden_path_only(path)\n }\n\n imp(dent)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":21,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp(path: &Path) -> bool {\n is_hidden_path_only(path)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":26,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp(path: &Path) -> bool {\n use std::os::windows::fs::MetadataExt;\n use winapi_util::file;\n\n if let Ok(md) = path.metadata() {\n if file::is_hidden(md.file_attributes() as u64) {\n return true;\n }\n }\n is_hidden_path_only(path)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":56,"symbol":"is_hidden_entry","kind":"function","lang":"rust","doc":"* The base name of the path starts with a `.`. * The file attributes have the `HIDDEN` property set. ## All other platforms This only returns true if the base name of the path starts with a `.`.","code":"pub(crate) fn is_hidden_entry(dent: &DirEntry) -> bool {\n #[cfg(not(windows))]\n fn imp(dent: &DirEntry) -> bool {\n is_hidden_path_only(dent.path())\n }\n\n #[cfg(windows)]\n fn imp(dent: &DirEntry) -> bool {\n use std::os::windows::fs::MetadataExt;\n use winapi_util::file;\n\n // This looks like we're doing an extra stat call, but on Windows, the\n // directory traverser reuses the metadata retrieved from each directory\n // entry and stores it on the DirEntry itself. So this is \"free.\"\n if let Ok(md) = dent.metadata() {\n if file::is_hidden(md.file_attributes() as u64) {\n return true;\n }\n }\n is_hidden_path_only(dent.path())\n }\n\n imp(dent)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":58,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp(dent: &DirEntry) -> bool {\n is_hidden_path_only(dent.path())\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":63,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp(dent: &DirEntry) -> bool {\n use std::os::windows::fs::MetadataExt;\n use winapi_util::file;\n\n // This looks like we're doing an extra stat call, but on Windows, the\n // directory traverser reuses the metadata retrieved from each directory\n // entry and stores it on the DirEntry itself. So this is \"free.\"\n if let Ok(md) = dent.metadata() {\n if file::is_hidden(md.file_attributes() as u64) {\n return true;\n }\n }\n is_hidden_path_only(dent.path())\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":85,"symbol":"is_hidden_path_only","kind":"function","lang":"rust","doc":"Returns true if and only if this path is considered to be hidden from only the path itself. This has the same behavior on all platforms.","code":"fn is_hidden_path_only(path: &Path) -> bool {\n if let Some(name) = file_name(path) {\n name.as_encoded_bytes().starts_with(b\".\")\n } else {\n false\n }\n}"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":96,"symbol":"strip_prefix","kind":"function","lang":"rust","doc":"Strip `prefix` from the `path` and return the remainder. If `path` doesn't have a prefix `prefix`, then return `None`.","code":"pub(crate) fn strip_prefix<'a, P: AsRef + ?Sized>(\n prefix: &'a P,\n path: &'a Path,\n) -> Option<&'a Path> {\n #[cfg(unix)]\n fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {\n use std::os::unix::ffi::OsStrExt;\n\n let prefix = prefix.as_os_str().as_bytes();\n let path = path.as_os_str().as_bytes();\n if prefix.len() > path.len() || prefix != &path[0..prefix.len()] {\n None\n } else {\n Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..])))\n }\n }\n\n #[cfg(not(unix))]\n fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {\n path.strip_prefix(prefix).ok()\n }\n\n imp(prefix.as_ref(), path)\n}"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":101,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {\n use std::os::unix::ffi::OsStrExt;\n\n let prefix = prefix.as_os_str().as_bytes();\n let path = path.as_os_str().as_bytes();\n if prefix.len() > path.len() || prefix != &path[0..prefix.len()] {\n None\n } else {\n Some(&Path::new(OsStr::from_bytes(&path[prefix.len()..])))\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":114,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp<'a>(prefix: &'a Path, path: &'a Path) -> Option<&'a Path> {\n path.strip_prefix(prefix).ok()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":123,"symbol":"is_file_name","kind":"function","lang":"rust","doc":"Returns true if this file path is just a file name. i.e., Its parent is the empty string.","code":"pub(crate) fn is_file_name>(path: P) -> bool {\n #[cfg(unix)]\n {\n memchr::memchr(b'/', path.as_ref().as_os_str().as_encoded_bytes())\n .is_none()\n }\n #[cfg(not(unix))]\n {\n path.as_ref()\n .parent()\n .map(|p| p.as_os_str().is_empty())\n .unwrap_or(false)\n }\n}"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":142,"symbol":"file_name","kind":"function","lang":"rust","doc":"The final component of the path, if it is a normal file. If the path terminates in `.`, `..`, or consists solely of a root of prefix, this will return `None`.","code":"pub(crate) fn file_name<'a, P: AsRef + ?Sized>(\n path: &'a P,\n) -> Option<&'a OsStr> {\n #[cfg(unix)]\n fn imp(path: &Path) -> Option<&OsStr> {\n use std::os::unix::ffi::OsStrExt;\n\n use memchr::memrchr;\n\n let path = path.as_os_str().as_bytes();\n if path.is_empty() {\n return None;\n } else if path.len() == 1 && path[0] == b'.' {\n return None;\n } else if path.last() == Some(&b'.') {\n return None;\n } else if path.len() >= 2 && &path[path.len() - 2..] == &b\"..\"[..] {\n return None;\n }\n let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0);\n Some(OsStr::from_bytes(&path[last_slash..]))\n }\n\n #[cfg(not(unix))]\n fn imp(path: &Path) -> Option<&OsStr> {\n path.file_name()\n }\n\n imp(path.as_ref())\n}"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":146,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp(path: &Path) -> Option<&OsStr> {\n use std::os::unix::ffi::OsStrExt;\n\n use memchr::memrchr;\n\n let path = path.as_os_str().as_bytes();\n if path.is_empty() {\n return None;\n } else if path.len() == 1 && path[0] == b'.' {\n return None;\n } else if path.last() == Some(&b'.') {\n return None;\n } else if path.len() >= 2 && &path[path.len() - 2..] == &b\"..\"[..] {\n return None;\n }\n let last_slash = memrchr(b'/', path).map(|i| i + 1).unwrap_or(0);\n Some(OsStr::from_bytes(&path[last_slash..]))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/pathutil.rs","line":166,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp(path: &Path) -> Option<&OsStr> {\n path.file_name()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":111,"symbol":"Glob","kind":"type","lang":"rust","doc":"For example, if there are one or more selections and a file path doesn't match any of those selections, then the file path is considered to be ignored. The lifetime `'a` refers to the lifetime of the underlying file type definition, which corresponds to the lifetime of the file type matcher.","code":"pub struct Glob<'a>(GlobInner<'a>);"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":114,"symbol":"GlobInner","kind":"type","lang":"rust","code":"enum GlobInner<'a> {\n /// No glob matched, but the file path should still be ignored.\n UnmatchedIgnore,\n /// A glob matched.\n Matched {\n /// The file type definition which provided the glob.\n def: &'a FileTypeDef,\n },\n}"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":125,"symbol":"unmatched","kind":"function","lang":"rust","code":"fn unmatched() -> Glob<'a> {\n Glob(GlobInner::UnmatchedIgnore)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":132,"symbol":"file_type_def","kind":"function","lang":"rust","doc":"Return the file type definition that matched, if one exists. A file type definition always exists when a specific definition matches a file path.","code":"pub fn file_type_def(&self) -> Option<&FileTypeDef> {\n match self {\n Glob(GlobInner::UnmatchedIgnore) => None,\n Glob(GlobInner::Matched { def, .. }) => Some(def),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":146,"symbol":"FileTypeDef","kind":"type","lang":"rust","doc":"A single file type definition. File type definitions can be retrieved in aggregate from a file type matcher. File type definitions are also reported when its responsible for a match.","code":"pub struct FileTypeDef {\n name: String,\n globs: Vec,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":153,"symbol":"name","kind":"function","lang":"rust","doc":"Return the name of this file type.","code":"pub fn name(&self) -> &str {\n &self.name\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":158,"symbol":"globs","kind":"function","lang":"rust","doc":"Return the globs used to recognize this file type.","code":"pub fn globs(&self) -> &[String] {\n &self.globs\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":165,"symbol":"Types","kind":"type","lang":"rust","doc":"Types is a file type matcher.","code":"pub struct Types {\n /// All of the file type definitions, sorted lexicographically by name.\n defs: Vec,\n /// All of the selections made by the user.\n selections: Vec>,\n /// Whether there is at least one Selection::Select in our selections.\n /// When this is true, a Match::None is converted to Match::Ignore.\n has_selected: bool,\n /// A mapping from glob index in the set to two indices. The first is an\n /// index into `selections` and the second is an index into the\n /// corresponding file type definition's list of globs.\n glob_to_selection: Vec<(usize, usize)>,\n /// The set of all glob selections, used for actual matching.\n set: GlobSet,\n /// Temporary storage for globs that match.\n matches: Arc>>,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":185,"symbol":"Selection","kind":"type","lang":"rust","doc":"Indicates the type of a selection for a particular file type.","code":"enum Selection {\n Select(String, T),\n Negate(String, T),\n}"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":191,"symbol":"is_negated","kind":"function","lang":"rust","code":"fn is_negated(&self) -> bool {\n match *self {\n Selection::Select(..) => false,\n Selection::Negate(..) => true,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":198,"symbol":"name","kind":"function","lang":"rust","code":"fn name(&self) -> &str {\n match *self {\n Selection::Select(ref name, _) => name,\n Selection::Negate(ref name, _) => name,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":205,"symbol":"map","kind":"function","lang":"rust","code":"fn map U>(self, f: F) -> Selection {\n match self {\n Selection::Select(name, inner) => {\n Selection::Select(name, f(inner))\n }\n Selection::Negate(name, inner) => {\n Selection::Negate(name, f(inner))\n }\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":216,"symbol":"inner","kind":"function","lang":"rust","code":"fn inner(&self) -> &T {\n match *self {\n Selection::Select(_, ref inner) => inner,\n Selection::Negate(_, ref inner) => inner,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":227,"symbol":"empty","kind":"function","lang":"rust","doc":"Creates a new file type matcher that never matches any path and contains no file type definitions.","code":"pub fn empty() -> Types {\n Types {\n defs: vec![],\n selections: vec![],\n has_selected: false,\n glob_to_selection: vec![],\n set: GlobSetBuilder::new().build().unwrap(),\n matches: Arc::new(Pool::with_available_parallelism_capacity(\n || vec![],\n )),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":241,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if and only if this matcher has zero selections.","code":"pub fn is_empty(&self) -> bool {\n self.selections.is_empty()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":246,"symbol":"len","kind":"function","lang":"rust","doc":"Returns the number of selections used in this matcher.","code":"pub fn len(&self) -> usize {\n self.selections.len()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":253,"symbol":"definitions","kind":"function","lang":"rust","doc":"Return the set of current file type definitions. Definitions and globs are sorted.","code":"pub fn definitions(&self) -> &[FileTypeDef] {\n &self.defs\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":263,"symbol":"matched","kind":"function","lang":"rust","doc":"Returns a match for the given path against this file type matcher. The path is considered whitelisted if it matches a selected file type. The path is considered ignored if it matches a negated file type. If at least one file type is selected and `path` doesn't match, then the path is also considered ignored.","code":"pub fn matched<'a, P: AsRef>(\n &'a self,\n path: P,\n is_dir: bool,\n ) -> Match> {\n // File types don't apply to directories, and we can't do anything\n // if our glob set is empty.\n if is_dir || self.set.is_empty() {\n return Match::None;\n }\n // We only want to match against the file name, so extract it.\n // If one doesn't exist, then we can't match it.\n let name = match file_name(path.as_ref()) {\n Some(name) => name,\n None if self.has_selected => {\n return Match::Ignore(Glob::unmatched());\n }\n None => {\n return Match::None;\n }\n };\n let mut matches = self.matches.get();\n self.set.matches_into(name, &mut *matches);\n // The highest precedent match is the last one.\n if let Some(&i) = matches.last() {\n let (isel, _) = self.glob_to_selection[i];\n let sel = &self.selections[isel];\n let glob = Glob(GlobInner::Matched { def: sel.inner() });\n return if sel.is_negated() {\n Match::Ignore(glob)\n } else {\n "} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":307,"symbol":"TypesBuilder","kind":"type","lang":"rust","doc":"TypesBuilder builds a type matcher from a set of file type definitions and a set of file type selections.","code":"pub struct TypesBuilder {\n types: HashMap,\n selections: Vec>,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":318,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for a file type matcher. The builder contains *no* type definitions to start with. A set of default type definitions can be added with `add_defaults`, and additional type definitions can be added with `select` and `negate`.","code":"pub fn new() -> TypesBuilder {\n TypesBuilder { types: HashMap::new(), selections: vec![] }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":324,"symbol":"build","kind":"function","lang":"rust","doc":"Build the current set of file type definitions *and* selections into a file type matcher.","code":"pub fn build(&self) -> Result {\n let defs = self.definitions();\n let has_selected = self.selections.iter().any(|s| !s.is_negated());\n\n let mut selections = vec![];\n let mut glob_to_selection = vec![];\n let mut build_set = GlobSetBuilder::new();\n for (isel, selection) in self.selections.iter().enumerate() {\n let def = match self.types.get(selection.name()) {\n Some(def) => def.clone(),\n None => {\n let name = selection.name().to_string();\n return Err(Error::UnrecognizedFileType(name));\n }\n };\n for (iglob, glob) in def.globs.iter().enumerate() {\n build_set.add(\n GlobBuilder::new(glob)\n .literal_separator(true)\n .build()\n .map_err(|err| Error::Glob {\n glob: Some(glob.to_string()),\n err: err.kind().to_string(),\n })?,\n );\n glob_to_selection.push((isel, iglob));\n }\n selections.push(selection.c"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":371,"symbol":"definitions","kind":"function","lang":"rust","doc":"Return the set of current file type definitions. Definitions and globs are sorted.","code":"pub fn definitions(&self) -> Vec {\n let mut defs = vec![];\n for def in self.types.values() {\n let mut def = def.clone();\n def.globs.sort();\n defs.push(def);\n }\n defs.sort_by(|def1, def2| def1.name().cmp(def2.name()));\n defs\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":385,"symbol":"select","kind":"function","lang":"rust","doc":"Select the file type given by `name`. If `name` is `all`, then all file types currently defined are selected.","code":"pub fn select(&mut self, name: &str) -> &mut TypesBuilder {\n if name == \"all\" {\n for name in self.types.keys() {\n self.selections.push(Selection::Select(name.to_string(), ()));\n }\n } else {\n self.selections.push(Selection::Select(name.to_string(), ()));\n }\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":399,"symbol":"negate","kind":"function","lang":"rust","doc":"Ignore the file type given by `name`. If `name` is `all`, then all file types currently defined are negated.","code":"pub fn negate(&mut self, name: &str) -> &mut TypesBuilder {\n if name == \"all\" {\n for name in self.types.keys() {\n self.selections.push(Selection::Negate(name.to_string(), ()));\n }\n } else {\n self.selections.push(Selection::Negate(name.to_string(), ()));\n }\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":411,"symbol":"clear","kind":"function","lang":"rust","doc":"Clear any file type definitions for the type name given.","code":"pub fn clear(&mut self, name: &str) -> &mut TypesBuilder {\n self.types.remove(name);\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":421,"symbol":"add","kind":"function","lang":"rust","doc":"Add a new file type definition. `name` can be arbitrary and `pat` should be a glob recognizing file paths belonging to the `name` type. If `name` is `all` or otherwise contains any character that is not a Unicode letter or number, then an error is returned.","code":"pub fn add(&mut self, name: &str, glob: &str) -> Result<(), Error> {\n if name == \"all\" || !name.chars().all(|c| c.is_alphanumeric()) {\n return Err(Error::InvalidDefinition);\n }\n let (key, glob) = (name.to_string(), glob.to_string());\n self.types\n .entry(key)\n .or_insert_with(|| FileTypeDef {\n name: name.to_string(),\n globs: vec![],\n })\n .globs\n .push(glob);\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":446,"symbol":"add_def","kind":"function","lang":"rust","doc":"given name with the given glob. 2. `{name}:include:{comma-separated list of already defined names}. This defines an 'include' definition that associates the given name with the definitions of the given existing types. Names may not include any characters that are not Unicode letters or numbers.","code":"pub fn add_def(&mut self, def: &str) -> Result<(), Error> {\n let parts: Vec<&str> = def.split(':').collect();\n match parts.len() {\n 2 => {\n let name = parts[0];\n let glob = parts[1];\n if name.is_empty() || glob.is_empty() {\n return Err(Error::InvalidDefinition);\n }\n self.add(name, glob)\n }\n 3 => {\n let name = parts[0];\n let types_string = parts[2];\n if name.is_empty()\n || parts[1] != \"include\"\n || types_string.is_empty()\n {\n return Err(Error::InvalidDefinition);\n }\n let types = types_string.split(',');\n // Check ahead of time to ensure that all types specified are\n // present and fail fast if not.\n if types.clone().any(|t| !self.types.contains_key(t)) {\n return Err(Error::InvalidDefinition);\n }\n for type_name in types {\n let globs =\n self.types.get(type_name).unwrap"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":486,"symbol":"add_defaults","kind":"function","lang":"rust","doc":"Add a set of default file type definitions.","code":"pub fn add_defaults(&mut self) -> &mut TypesBuilder {\n static MSG: &'static str = \"adding a default type should never fail\";\n for &(names, exts) in DEFAULT_TYPES {\n for name in names {\n for ext in exts {\n self.add(name, ext).expect(MSG);\n }\n }\n }\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":533,"symbol":"types","kind":"function","lang":"rust","code":"fn types() -> Vec<&'static str> {\n vec![\n \"html:*.html\",\n \"html:*.htm\",\n \"rust:*.rs\",\n \"js:*.js\",\n \"py:*.py\",\n \"python:*.py\",\n \"foo:*.{rs,foo}\",\n \"combo:include:html,rust\",\n ]\n }"} {"repo":"ripgrep","file":"crates/ignore/src/types.rs","line":568,"symbol":"test_invalid_defs","kind":"function","lang":"rust","code":"fn test_invalid_defs() {\n let mut btypes = TypesBuilder::new();\n for tydef in types() {\n btypes.add_def(tydef).unwrap();\n }\n // Preserve the original definitions for later comparison.\n let original_defs = btypes.definitions();\n let bad_defs = vec![\n // Reference to type that does not exist\n \"combo:include:html,qwerty\",\n // Bad format\n \"combo:foobar:html,rust\",\n \"\",\n ];\n for def in bad_defs {\n assert!(btypes.add_def(def).is_err());\n // Ensure that nothing changed, even if some of the includes were valid.\n assert_eq!(btypes.definitions(), original_defs);\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":31,"symbol":"DirEntry","kind":"type","lang":"rust","doc":"A directory entry with a possible error attached. The error typically refers to a problem parsing ignore files in a particular directory.","code":"pub struct DirEntry {\n dent: DirEntryInner,\n err: Option,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":38,"symbol":"path","kind":"function","lang":"rust","doc":"The full path that this entry represents.","code":"pub fn path(&self) -> &Path {\n self.dent.path()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":44,"symbol":"into_path","kind":"function","lang":"rust","doc":"The full path that this entry represents. Analogous to [`DirEntry::path`], but moves ownership of the path.","code":"pub fn into_path(self) -> PathBuf {\n self.dent.into_path()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":49,"symbol":"path_is_symlink","kind":"function","lang":"rust","doc":"Whether this entry corresponds to a symbolic link or not.","code":"pub fn path_is_symlink(&self) -> bool {\n self.dent.path_is_symlink()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":56,"symbol":"is_stdin","kind":"function","lang":"rust","doc":"Returns true if and only if this entry corresponds to stdin. i.e., The entry has depth 0 and its file name is `-`.","code":"pub fn is_stdin(&self) -> bool {\n self.dent.is_stdin()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":61,"symbol":"metadata","kind":"function","lang":"rust","doc":"Return the metadata for the file that this entry points to.","code":"pub fn metadata(&self) -> Result {\n self.dent.metadata()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":68,"symbol":"file_type","kind":"function","lang":"rust","doc":"Return the file type for the file that this entry points to. This entry doesn't have a file type if it corresponds to stdin.","code":"pub fn file_type(&self) -> Option {\n self.dent.file_type()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":76,"symbol":"file_name","kind":"function","lang":"rust","doc":"Return the file name of this entry. If this entry has no file name (e.g., `/`), then the full path is returned.","code":"pub fn file_name(&self) -> &OsStr {\n self.dent.file_name()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":81,"symbol":"depth","kind":"function","lang":"rust","doc":"Returns the depth at which this entry was created relative to the root.","code":"pub fn depth(&self) -> usize {\n self.dent.depth()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":89,"symbol":"ino","kind":"function","lang":"rust","doc":"Returns the underlying inode number if one exists. If this entry doesn't have an inode number, then `None` is returned.","code":"pub fn ino(&self) -> Option {\n self.dent.ino()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":98,"symbol":"error","kind":"function","lang":"rust","doc":"Returns an error, if one exists, associated with processing this entry. An example of an error is one that occurred while parsing an ignore file. Errors related to traversing a directory tree itself are reported as part of yielding the directory entry, and not with this method.","code":"pub fn error(&self) -> Option<&Error> {\n self.err.as_ref()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":103,"symbol":"is_dir","kind":"function","lang":"rust","doc":"Returns true if and only if this entry points to a directory.","code":"pub(crate) fn is_dir(&self) -> bool {\n self.dent.is_dir()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":107,"symbol":"new_stdin","kind":"function","lang":"rust","code":"fn new_stdin() -> DirEntry {\n DirEntry { dent: DirEntryInner::Stdin, err: None }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":111,"symbol":"new_walkdir","kind":"function","lang":"rust","code":"fn new_walkdir(dent: walkdir::DirEntry, err: Option) -> DirEntry {\n DirEntry { dent: DirEntryInner::Walkdir(dent), err }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":115,"symbol":"new_raw","kind":"function","lang":"rust","code":"fn new_raw(dent: DirEntryRaw, err: Option) -> DirEntry {\n DirEntry { dent: DirEntryInner::Raw(dent), err }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":131,"symbol":"DirEntryInner","kind":"type","lang":"rust","doc":"1. From the walkdir crate. 2. Special entries that represent things like stdin. 3. From a path. Specifically, (3) has to essentially re-create the DirEntry implementation from WalkDir.","code":"enum DirEntryInner {\n Stdin,\n Walkdir(walkdir::DirEntry),\n Raw(DirEntryRaw),\n}"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":138,"symbol":"path","kind":"function","lang":"rust","code":"fn path(&self) -> &Path {\n use self::DirEntryInner::*;\n match *self {\n Stdin => Path::new(\"\"),\n Walkdir(ref x) => x.path(),\n Raw(ref x) => x.path(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":147,"symbol":"into_path","kind":"function","lang":"rust","code":"fn into_path(self) -> PathBuf {\n use self::DirEntryInner::*;\n match self {\n Stdin => PathBuf::from(\"\"),\n Walkdir(x) => x.into_path(),\n Raw(x) => x.into_path(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":156,"symbol":"path_is_symlink","kind":"function","lang":"rust","code":"fn path_is_symlink(&self) -> bool {\n use self::DirEntryInner::*;\n match *self {\n Stdin => false,\n Walkdir(ref x) => x.path_is_symlink(),\n Raw(ref x) => x.path_is_symlink(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":165,"symbol":"is_stdin","kind":"function","lang":"rust","code":"fn is_stdin(&self) -> bool {\n match *self {\n DirEntryInner::Stdin => true,\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":172,"symbol":"metadata","kind":"function","lang":"rust","code":"fn metadata(&self) -> Result {\n use self::DirEntryInner::*;\n match *self {\n Stdin => {\n let err = Error::Io(io::Error::new(\n io::ErrorKind::Other,\n \" has no metadata\",\n ));\n Err(err.with_path(\"\"))\n }\n Walkdir(ref x) => x.metadata().map_err(|err| {\n Error::Io(io::Error::from(err))\n .with_depth(x.depth())\n .with_path(x.path())\n }),\n Raw(ref x) => x.metadata(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":191,"symbol":"file_type","kind":"function","lang":"rust","code":"fn file_type(&self) -> Option {\n use self::DirEntryInner::*;\n match *self {\n Stdin => None,\n Walkdir(ref x) => Some(x.file_type()),\n Raw(ref x) => Some(x.file_type()),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":200,"symbol":"file_name","kind":"function","lang":"rust","code":"fn file_name(&self) -> &OsStr {\n use self::DirEntryInner::*;\n match *self {\n Stdin => OsStr::new(\"\"),\n Walkdir(ref x) => x.file_name(),\n Raw(ref x) => x.file_name(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":209,"symbol":"depth","kind":"function","lang":"rust","code":"fn depth(&self) -> usize {\n use self::DirEntryInner::*;\n match *self {\n Stdin => 0,\n Walkdir(ref x) => x.depth(),\n Raw(ref x) => x.depth(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":219,"symbol":"ino","kind":"function","lang":"rust","code":"fn ino(&self) -> Option {\n use self::DirEntryInner::*;\n use walkdir::DirEntryExt;\n match *self {\n Stdin => None,\n Walkdir(ref x) => Some(x.ino()),\n Raw(ref x) => Some(x.ino()),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":230,"symbol":"is_dir","kind":"function","lang":"rust","doc":"Returns true if and only if this entry points to a directory.","code":"fn is_dir(&self) -> bool {\n self.file_type().map(|ft| ft.is_dir()).unwrap_or(false)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":238,"symbol":"DirEntryRaw","kind":"type","lang":"rust","doc":"DirEntryRaw is essentially copied from the walkdir crate so that we can build `DirEntry`s from whole cloth in the parallel iterator.","code":"struct DirEntryRaw {\n /// The path as reported by the `fs::ReadDir` iterator (even if it's a\n /// symbolic link).\n path: PathBuf,\n /// The file type. Necessary for recursive iteration, so store it.\n ty: FileType,\n /// Is set when this entry was created from a symbolic link and the user\n /// expects the iterator to follow symbolic links.\n follow_link: bool,\n /// The depth at which this entry was generated relative to the root.\n depth: usize,\n /// The underlying inode number (Unix only).\n #[cfg(unix)]\n ino: u64,\n /// The underlying metadata (Windows only). We store this on Windows\n /// because this comes for free while reading a directory.\n #[cfg(windows)]\n metadata: fs::Metadata,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":259,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n // Leaving out FileType because it doesn't have a debug impl\n // in Rust 1.9. We could add it if we really wanted to by manually\n // querying each possibly file type. Meh. ---AG\n f.debug_struct(\"DirEntryRaw\")\n .field(\"path\", &self.path)\n .field(\"follow_link\", &self.follow_link)\n .field(\"depth\", &self.depth)\n .finish()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":272,"symbol":"path","kind":"function","lang":"rust","code":"fn path(&self) -> &Path {\n &self.path\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":276,"symbol":"into_path","kind":"function","lang":"rust","code":"fn into_path(self) -> PathBuf {\n self.path\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":280,"symbol":"path_is_symlink","kind":"function","lang":"rust","code":"fn path_is_symlink(&self) -> bool {\n self.ty.is_symlink() || self.follow_link\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":284,"symbol":"metadata","kind":"function","lang":"rust","code":"fn metadata(&self) -> Result {\n self.metadata_internal()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":289,"symbol":"metadata_internal","kind":"function","lang":"rust","code":"fn metadata_internal(&self) -> Result {\n if self.follow_link {\n fs::metadata(&self.path)\n } else {\n Ok(self.metadata.clone())\n }\n .map_err(|err| Error::Io(io::Error::from(err)).with_path(&self.path))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":299,"symbol":"metadata_internal","kind":"function","lang":"rust","code":"fn metadata_internal(&self) -> Result {\n if self.follow_link {\n fs::metadata(&self.path)\n } else {\n fs::symlink_metadata(&self.path)\n }\n .map_err(|err| {\n Error::Io(err).with_depth(self.depth).with_path(&self.path)\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":310,"symbol":"file_type","kind":"function","lang":"rust","code":"fn file_type(&self) -> FileType {\n self.ty\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":314,"symbol":"file_name","kind":"function","lang":"rust","code":"fn file_name(&self) -> &OsStr {\n self.path.file_name().unwrap_or_else(|| self.path.as_os_str())\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":318,"symbol":"depth","kind":"function","lang":"rust","code":"fn depth(&self) -> usize {\n self.depth\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":323,"symbol":"ino","kind":"function","lang":"rust","code":"fn ino(&self) -> u64 {\n self.ino\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":327,"symbol":"from_entry","kind":"function","lang":"rust","code":"fn from_entry(\n depth: usize,\n ent: &fs::DirEntry,\n ) -> Result {\n let ty = ent.file_type().map_err(|err| {\n let err = Error::Io(err).with_depth(depth).with_path(ent.path());\n Error::WithDepth { depth, err: Box::new(err) }\n })?;\n DirEntryRaw::from_entry_os(depth, ent, ty)\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":339,"symbol":"from_entry_os","kind":"function","lang":"rust","code":"fn from_entry_os(\n depth: usize,\n ent: &fs::DirEntry,\n ty: fs::FileType,\n ) -> Result {\n let md = ent.metadata().map_err(|err| {\n let err = Error::Io(err).with_depth(depth).with_path(ent.path());\n Error::WithDepth { depth, err: Box::new(err) }\n })?;\n Ok(DirEntryRaw {\n path: ent.path(),\n ty,\n follow_link: false,\n depth,\n metadata: md,\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":358,"symbol":"from_entry_os","kind":"function","lang":"rust","code":"fn from_entry_os(\n depth: usize,\n ent: &fs::DirEntry,\n ty: fs::FileType,\n ) -> Result {\n use std::os::unix::fs::DirEntryExt;\n\n Ok(DirEntryRaw {\n path: ent.path(),\n ty,\n follow_link: false,\n depth,\n ino: ent.ino(),\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":377,"symbol":"from_entry_os","kind":"function","lang":"rust","doc":"Placeholder implementation to allow compiling on non-standard platforms (e.g. wasm32).","code":"fn from_entry_os(\n depth: usize,\n ent: &fs::DirEntry,\n ty: fs::FileType,\n ) -> Result {\n Err(Error::Io(io::Error::new(\n io::ErrorKind::Other,\n \"unsupported platform\",\n )))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":389,"symbol":"from_path","kind":"function","lang":"rust","code":"fn from_path(\n depth: usize,\n pb: PathBuf,\n link: bool,\n ) -> Result {\n let md = fs::metadata(&pb)\n .map_err(|err| Error::Io(err).with_depth(depth).with_path(&pb))?;\n Ok(DirEntryRaw {\n path: pb,\n ty: md.file_type(),\n follow_link: link,\n depth,\n metadata: md,\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":406,"symbol":"from_path","kind":"function","lang":"rust","code":"fn from_path(\n depth: usize,\n pb: PathBuf,\n link: bool,\n ) -> Result {\n use std::os::unix::fs::MetadataExt;\n\n let md = fs::metadata(&pb)\n .map_err(|err| Error::Io(err).with_depth(depth).with_path(&pb))?;\n Ok(DirEntryRaw {\n path: pb,\n ty: md.file_type(),\n follow_link: link,\n depth,\n ino: md.ino(),\n })\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":427,"symbol":"from_path","kind":"function","lang":"rust","doc":"Placeholder implementation to allow compiling on non-standard platforms (e.g. wasm32).","code":"fn from_path(\n depth: usize,\n pb: PathBuf,\n link: bool,\n ) -> Result {\n Err(Error::Io(io::Error::new(\n io::ErrorKind::Other,\n \"unsupported platform\",\n )))\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":488,"symbol":"WalkBuilder","kind":"type","lang":"rust","doc":"* Fifth, if the path hasn't been whitelisted and it is hidden, then the path is skipped. * Sixth, unless the path is a directory, the size of the file is compared against the max filesize limit. If it exceeds the limit, it is skipped. * Seventh, if the path has made it this far then it is yielded in the iterator.","code":"pub struct WalkBuilder {\n paths: Vec,\n ig_builder: IgnoreBuilder,\n max_depth: Option,\n min_depth: Option,\n max_filesize: Option,\n follow_links: bool,\n same_file_system: bool,\n sorter: Option,\n threads: usize,\n skip: Option>,\n filter: Option,\n /// The directory that gitignores should be interpreted relative to.\n ///\n /// Usually this is the directory containing the gitignore file. But in\n /// some cases, like for global gitignores or for gitignores specified\n /// explicitly, this should generally be set to the current working\n /// directory. This is only used for global gitignores or \"explicit\"\n /// gitignores.\n ///\n /// When `None`, the CWD is fetched from `std::env::current_dir()`. If\n /// that fails, then global gitignores are ignored (an error is logged).\n global_gitignores_relative_to:\n OnceLock>>,\n}"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":515,"symbol":"Sorter","kind":"type","lang":"rust","code":"enum Sorter {\n ByName(Arc Ordering + Send + Sync + 'static>),\n ByPath(Arc Ordering + Send + Sync + 'static>),\n}"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":521,"symbol":"Filter","kind":"type","lang":"rust","code":"struct Filter(Arc bool + Send + Sync + 'static>);"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":524,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n f.debug_struct(\"WalkBuilder\")\n .field(\"paths\", &self.paths)\n .field(\"ig_builder\", &self.ig_builder)\n .field(\"max_depth\", &self.max_depth)\n .field(\"min_depth\", &self.min_depth)\n .field(\"max_filesize\", &self.max_filesize)\n .field(\"follow_links\", &self.follow_links)\n .field(\"same_file_system\", &self.same_file_system)\n .field(\"sorter\", &\"<...>\")\n .field(\"threads\", &self.threads)\n .field(\"skip\", &self.skip)\n .field(\"filter\", &\"<...>\")\n .field(\n \"global_gitignores_relative_to\",\n &self.global_gitignores_relative_to,\n )\n .finish()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":552,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for a recursive directory iterator for the directory given. Note that if you want to traverse multiple different directories, it is better to call `add` on this builder than to create multiple `Walk` values.","code":"pub fn new>(path: P) -> WalkBuilder {\n WalkBuilder::from_iter([path])\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":560,"symbol":"empty","kind":"function","lang":"rust","doc":"Create an empty builder to which paths can be added. Note that if you call `build` on this instance before calling `add` on it, it will return exactly zero items during iteration.","code":"pub fn empty() -> WalkBuilder {\n WalkBuilder {\n paths: vec![],\n ig_builder: IgnoreBuilder::new(),\n max_depth: None,\n min_depth: None,\n max_filesize: None,\n follow_links: false,\n same_file_system: false,\n sorter: None,\n threads: 0,\n skip: None,\n filter: None,\n global_gitignores_relative_to: OnceLock::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":582,"symbol":"from_iter","kind":"function","lang":"rust","doc":"Create a new builder for a recursive directory iterator from the sequence of paths. Note that if the iterator is empty, this is the same as `WalkBuilder::empty`.","code":"pub fn from_iter, I: IntoIterator>(\n paths: I,\n ) -> WalkBuilder {\n let mut builder = WalkBuilder::empty();\n for path in paths.into_iter() {\n builder.add(path);\n }\n builder\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":593,"symbol":"build","kind":"function","lang":"rust","doc":"Build a new `Walk` iterator.","code":"pub fn build(&self) -> Walk {\n let follow_links = self.follow_links;\n let max_depth = self.max_depth;\n let min_depth = self.min_depth;\n let sorter = self.sorter.clone();\n let its = self\n .paths\n .iter()\n .map(move |p| {\n if p == Path::new(\"-\") {\n (p.to_path_buf(), None)\n } else {\n let mut wd = WalkDir::new(p);\n wd = wd.follow_links(follow_links || p.is_file());\n wd = wd.same_file_system(self.same_file_system);\n if let Some(max_depth) = max_depth {\n wd = wd.max_depth(max_depth);\n }\n if let Some(min_depth) = min_depth {\n wd = wd.min_depth(min_depth);\n }\n if let Some(ref sorter) = sorter {\n match sorter.clone() {\n Sorter::ByName(cmp) => {\n wd = wd.sort_by(move |a, b| {\n cmp(a.file_name(), b.file_name())\n });\n "} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":675,"symbol":"build_matchers","kind":"function","lang":"rust","doc":"[`IncrementalIgnore::matched_with_errors`]. Once an ignore file has been loaded, changes to it are not observed. Build new matchers to reload changed ignore files. Matchers built together share the builder's base ignore configuration and compiled parent matchers.","code":"pub fn build_matchers(&self) -> Vec {\n let ignore = self.build_ignore();\n let options = IncrementalIgnoreOptions {\n min_depth: self.min_depth,\n max_depth: self.max_depth,\n max_filesize: self.max_filesize,\n hidden: self.ig_builder.is_hidden(),\n follow_links: self.follow_links,\n };\n self.paths\n .iter()\n .map(move |path| {\n IncrementalIgnore::new(\n path.clone(),\n ignore.clone(),\n options.clone(),\n )\n })\n .collect()\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":701,"symbol":"build_parallel","kind":"function","lang":"rust","doc":"Build a new `WalkParallel` iterator. Note that this *doesn't* return something that implements `Iterator`. Instead, the returned value must be run with a closure. e.g., `builder.build_parallel().run(|| |path| { println!(\"{path:?}\"); WalkState::Continue })`.","code":"pub fn build_parallel(&self) -> WalkParallel {\n let ig_root = self.build_ignore();\n WalkParallel {\n paths: self.paths.clone().into_iter(),\n ig_root,\n max_depth: self.max_depth,\n min_depth: self.min_depth,\n max_filesize: self.max_filesize,\n follow_links: self.follow_links,\n same_file_system: self.same_file_system,\n threads: self.threads,\n skip: self.skip.clone(),\n filter: self.filter.clone(),\n }\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":722,"symbol":"add","kind":"function","lang":"rust","doc":"Add a file path to the iterator. Each additional file path added is traversed recursively. This should be preferred over building multiple `Walk` iterators since this enables reusing resources across iteration.","code":"pub fn add>(&mut self, path: P) -> &mut WalkBuilder {\n self.paths.push(path.as_ref().to_path_buf());\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":730,"symbol":"max_depth","kind":"function","lang":"rust","doc":"The maximum depth to recurse. The default, `None`, imposes no depth restriction.","code":"pub fn max_depth(&mut self, depth: Option) -> &mut WalkBuilder {\n self.max_depth = depth;\n if self.min_depth.is_some()\n && self.max_depth.is_some()\n && self.max_depth < self.min_depth\n {\n self.max_depth = self.min_depth;\n }\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":744,"symbol":"min_depth","kind":"function","lang":"rust","doc":"The minimum depth to recurse. The default, `None`, imposes no minimum depth restriction.","code":"pub fn min_depth(&mut self, depth: Option) -> &mut WalkBuilder {\n self.min_depth = depth;\n if self.max_depth.is_some()\n && self.min_depth.is_some()\n && self.min_depth > self.max_depth\n {\n self.min_depth = self.max_depth;\n }\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":756,"symbol":"follow_links","kind":"function","lang":"rust","doc":"Whether to follow symbolic links or not.","code":"pub fn follow_links(&mut self, yes: bool) -> &mut WalkBuilder {\n self.follow_links = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/src/walk.rs","line":762,"symbol":"max_filesize","kind":"function","lang":"rust","doc":"Whether to ignore files above the specified limit.","code":"pub fn max_filesize(&mut self, filesize: Option) -> &mut WalkBuilder {\n self.max_filesize = filesize;\n self\n }"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":6,"symbol":"file_root_00","kind":"field","lang":"gitignore","code":"file_root_00"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":9,"symbol":"file_root_01/","kind":"field","lang":"gitignore","code":"file_root_01/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":12,"symbol":"file_root_02/*","kind":"field","lang":"gitignore","code":"file_root_02/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":15,"symbol":"file_root_03/**","kind":"field","lang":"gitignore","code":"file_root_03/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":19,"symbol":"/file_root_10","kind":"field","lang":"gitignore","code":"/file_root_10"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":22,"symbol":"/file_root_11/","kind":"field","lang":"gitignore","code":"/file_root_11/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":25,"symbol":"/file_root_12/*","kind":"field","lang":"gitignore","code":"/file_root_12/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":28,"symbol":"/file_root_13/**","kind":"field","lang":"gitignore","code":"/file_root_13/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":32,"symbol":"*/file_root_20","kind":"field","lang":"gitignore","code":"*/file_root_20"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":35,"symbol":"*/file_root_21/","kind":"field","lang":"gitignore","code":"*/file_root_21/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":38,"symbol":"*/file_root_22/*","kind":"field","lang":"gitignore","code":"*/file_root_22/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":41,"symbol":"*/file_root_23/**","kind":"field","lang":"gitignore","code":"*/file_root_23/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":45,"symbol":"**/file_root_30","kind":"field","lang":"gitignore","code":"**/file_root_30"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":48,"symbol":"**/file_root_31/","kind":"field","lang":"gitignore","code":"**/file_root_31/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":51,"symbol":"**/file_root_32/*","kind":"field","lang":"gitignore","code":"**/file_root_32/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":54,"symbol":"**/file_root_33/**","kind":"field","lang":"gitignore","code":"**/file_root_33/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":60,"symbol":"file_deep_00","kind":"field","lang":"gitignore","code":"file_deep_00"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":63,"symbol":"file_deep_01/","kind":"field","lang":"gitignore","code":"file_deep_01/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":66,"symbol":"file_deep_02/*","kind":"field","lang":"gitignore","code":"file_deep_02/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":69,"symbol":"file_deep_03/**","kind":"field","lang":"gitignore","code":"file_deep_03/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":73,"symbol":"/file_deep_10","kind":"field","lang":"gitignore","code":"/file_deep_10"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":76,"symbol":"/file_deep_11/","kind":"field","lang":"gitignore","code":"/file_deep_11/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":79,"symbol":"/file_deep_12/*","kind":"field","lang":"gitignore","code":"/file_deep_12/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":82,"symbol":"/file_deep_13/**","kind":"field","lang":"gitignore","code":"/file_deep_13/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":86,"symbol":"*/file_deep_20","kind":"field","lang":"gitignore","code":"*/file_deep_20"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":89,"symbol":"*/file_deep_21/","kind":"field","lang":"gitignore","code":"*/file_deep_21/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":92,"symbol":"*/file_deep_22/*","kind":"field","lang":"gitignore","code":"*/file_deep_22/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":95,"symbol":"*/file_deep_23/**","kind":"field","lang":"gitignore","code":"*/file_deep_23/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":99,"symbol":"**/file_deep_30","kind":"field","lang":"gitignore","code":"**/file_deep_30"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":102,"symbol":"**/file_deep_31/","kind":"field","lang":"gitignore","code":"**/file_deep_31/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":105,"symbol":"**/file_deep_32/*","kind":"field","lang":"gitignore","code":"**/file_deep_32/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":108,"symbol":"**/file_deep_33/**","kind":"field","lang":"gitignore","code":"**/file_deep_33/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":114,"symbol":"dir_root_00","kind":"field","lang":"gitignore","code":"dir_root_00"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":117,"symbol":"dir_root_01/","kind":"field","lang":"gitignore","code":"dir_root_01/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":120,"symbol":"dir_root_02/*","kind":"field","lang":"gitignore","code":"dir_root_02/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":123,"symbol":"dir_root_03/**","kind":"field","lang":"gitignore","code":"dir_root_03/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":127,"symbol":"/dir_root_10","kind":"field","lang":"gitignore","code":"/dir_root_10"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":130,"symbol":"/dir_root_11/","kind":"field","lang":"gitignore","code":"/dir_root_11/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":133,"symbol":"/dir_root_12/*","kind":"field","lang":"gitignore","code":"/dir_root_12/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":136,"symbol":"/dir_root_13/**","kind":"field","lang":"gitignore","code":"/dir_root_13/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":140,"symbol":"*/dir_root_20","kind":"field","lang":"gitignore","code":"*/dir_root_20"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":143,"symbol":"*/dir_root_21/","kind":"field","lang":"gitignore","code":"*/dir_root_21/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":146,"symbol":"*/dir_root_22/*","kind":"field","lang":"gitignore","code":"*/dir_root_22/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":149,"symbol":"*/dir_root_23/**","kind":"field","lang":"gitignore","code":"*/dir_root_23/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":153,"symbol":"**/dir_root_30","kind":"field","lang":"gitignore","code":"**/dir_root_30"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":156,"symbol":"**/dir_root_31/","kind":"field","lang":"gitignore","code":"**/dir_root_31/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":159,"symbol":"**/dir_root_32/*","kind":"field","lang":"gitignore","code":"**/dir_root_32/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":162,"symbol":"**/dir_root_33/**","kind":"field","lang":"gitignore","code":"**/dir_root_33/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":168,"symbol":"dir_deep_00","kind":"field","lang":"gitignore","code":"dir_deep_00"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":171,"symbol":"dir_deep_01/","kind":"field","lang":"gitignore","code":"dir_deep_01/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":174,"symbol":"dir_deep_02/*","kind":"field","lang":"gitignore","code":"dir_deep_02/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":177,"symbol":"dir_deep_03/**","kind":"field","lang":"gitignore","code":"dir_deep_03/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":181,"symbol":"/dir_deep_10","kind":"field","lang":"gitignore","code":"/dir_deep_10"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":184,"symbol":"/dir_deep_11/","kind":"field","lang":"gitignore","code":"/dir_deep_11/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":187,"symbol":"/dir_deep_12/*","kind":"field","lang":"gitignore","code":"/dir_deep_12/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":190,"symbol":"/dir_deep_13/**","kind":"field","lang":"gitignore","code":"/dir_deep_13/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":194,"symbol":"*/dir_deep_20","kind":"field","lang":"gitignore","code":"*/dir_deep_20"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":197,"symbol":"*/dir_deep_21/","kind":"field","lang":"gitignore","code":"*/dir_deep_21/"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":200,"symbol":"*/dir_deep_22/*","kind":"field","lang":"gitignore","code":"*/dir_deep_22/*"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.gitignore","line":203,"symbol":"*/dir_deep_23/**","kind":"field","lang":"gitignore","code":"*/dir_deep_23/**"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.rs","line":8,"symbol":"get_gitignore","kind":"function","lang":"rust","code":"fn get_gitignore() -> Gitignore {\n let mut builder = GitignoreBuilder::new(\"ROOT\");\n let error = builder.add(IGNORE_FILE);\n assert!(error.is_none(), \"failed to open gitignore file\");\n builder.build().unwrap()\n}"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.rs","line":17,"symbol":"test_path_should_be_under_root","kind":"function","lang":"rust","code":"fn test_path_should_be_under_root() {\n let gitignore = get_gitignore();\n let path = \"/tmp/some_file\";\n gitignore.matched_path_or_any_parents(Path::new(path), false);\n assert!(false);\n}"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.rs","line":25,"symbol":"test_files_in_root","kind":"function","lang":"rust","code":"fn test_files_in_root() {\n let gitignore = get_gitignore();\n let m = |path: &str| {\n gitignore.matched_path_or_any_parents(Path::new(path), false)\n };\n\n // 0x\n assert!(m(\"ROOT/file_root_00\").is_ignore());\n assert!(m(\"ROOT/file_root_01\").is_none());\n assert!(m(\"ROOT/file_root_02\").is_none());\n assert!(m(\"ROOT/file_root_03\").is_none());\n\n // 1x\n assert!(m(\"ROOT/file_root_10\").is_ignore());\n assert!(m(\"ROOT/file_root_11\").is_none());\n assert!(m(\"ROOT/file_root_12\").is_none());\n assert!(m(\"ROOT/file_root_13\").is_none());\n\n // 2x\n assert!(m(\"ROOT/file_root_20\").is_none());\n assert!(m(\"ROOT/file_root_21\").is_none());\n assert!(m(\"ROOT/file_root_22\").is_none());\n assert!(m(\"ROOT/file_root_23\").is_none());\n\n // 3x\n assert!(m(\"ROOT/file_root_30\").is_ignore());\n assert!(m(\"ROOT/file_root_31\").is_none());\n assert!(m(\"ROOT/file_root_32\").is_none());\n assert!(m(\"ROOT/file_root_33\").is_none());\n}"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.rs","line":57,"symbol":"test_files_in_deep","kind":"function","lang":"rust","code":"fn test_files_in_deep() {\n let gitignore = get_gitignore();\n let m = |path: &str| {\n gitignore.matched_path_or_any_parents(Path::new(path), false)\n };\n\n // 0x\n assert!(m(\"ROOT/parent_dir/file_deep_00\").is_ignore());\n assert!(m(\"ROOT/parent_dir/file_deep_01\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_02\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_03\").is_none());\n\n // 1x\n assert!(m(\"ROOT/parent_dir/file_deep_10\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_11\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_12\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_13\").is_none());\n\n // 2x\n assert!(m(\"ROOT/parent_dir/file_deep_20\").is_ignore());\n assert!(m(\"ROOT/parent_dir/file_deep_21\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_22\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_23\").is_none());\n\n // 3x\n assert!(m(\"ROOT/parent_dir/file_deep_30\").is_ignore());\n assert!(m(\"ROOT/parent_dir/file_deep_31\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_32\").is_none());\n assert!(m(\"ROOT/parent_dir/file_deep_33\").is_none());\n}"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.rs","line":89,"symbol":"test_dirs_in_root","kind":"function","lang":"rust","code":"fn test_dirs_in_root() {\n let gitignore = get_gitignore();\n let m = |path: &str, is_dir: bool| {\n gitignore.matched_path_or_any_parents(Path::new(path), is_dir)\n };\n\n // 00\n assert!(m(\"ROOT/dir_root_00\", true).is_ignore());\n assert!(m(\"ROOT/dir_root_00/file\", false).is_ignore());\n assert!(m(\"ROOT/dir_root_00/child_dir\", true).is_ignore());\n assert!(m(\"ROOT/dir_root_00/child_dir/file\", false).is_ignore());\n\n // 01\n assert!(m(\"ROOT/dir_root_01\", true).is_ignore());\n assert!(m(\"ROOT/dir_root_01/file\", false).is_ignore());\n assert!(m(\"ROOT/dir_root_01/child_dir\", true).is_ignore());\n assert!(m(\"ROOT/dir_root_01/child_dir/file\", false).is_ignore());\n\n // 02\n assert!(m(\"ROOT/dir_root_02\", true).is_none()); // dir itself doesn't match\n assert!(m(\"ROOT/dir_root_02/file\", false).is_ignore());\n assert!(m(\"ROOT/dir_root_02/child_dir\", true).is_ignore());\n assert!(m(\"ROOT/dir_root_02/child_dir/file\", false).is_ignore());\n\n // 03\n assert!(m(\"ROOT/dir_root_03\", true).is_none()); // dir itself doesn't match\n assert!(m(\"ROOT/dir_root_03/file\", false).is_ignore());\n assert!(m(\"ROOT/dir_root_03/child_dir\", true).is_ignore());\n "} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_matched_path_or_any_parents_tests.rs","line":193,"symbol":"test_dirs_in_deep","kind":"function","lang":"rust","code":"fn test_dirs_in_deep() {\n let gitignore = get_gitignore();\n let m = |path: &str, is_dir: bool| {\n gitignore.matched_path_or_any_parents(Path::new(path), is_dir)\n };\n\n // 00\n assert!(m(\"ROOT/parent_dir/dir_deep_00\", true).is_ignore());\n assert!(m(\"ROOT/parent_dir/dir_deep_00/file\", false).is_ignore());\n assert!(m(\"ROOT/parent_dir/dir_deep_00/child_dir\", true).is_ignore());\n assert!(\n m(\"ROOT/parent_dir/dir_deep_00/child_dir/file\", false).is_ignore()\n );\n\n // 01\n assert!(m(\"ROOT/parent_dir/dir_deep_01\", true).is_ignore());\n assert!(m(\"ROOT/parent_dir/dir_deep_01/file\", false).is_ignore());\n assert!(m(\"ROOT/parent_dir/dir_deep_01/child_dir\", true).is_ignore());\n assert!(\n m(\"ROOT/parent_dir/dir_deep_01/child_dir/file\", false).is_ignore()\n );\n\n // 02\n assert!(m(\"ROOT/parent_dir/dir_deep_02\", true).is_none());\n assert!(m(\"ROOT/parent_dir/dir_deep_02/file\", false).is_none());\n assert!(m(\"ROOT/parent_dir/dir_deep_02/child_dir\", true).is_none());\n assert!(m(\"ROOT/parent_dir/dir_deep_02/child_dir/file\", false).is_none());\n\n // 03\n assert!(m(\"ROOT/parent_dir/dir_deep_03\", true).is_none());\n assert!(m(\"R"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_skip_bom.gitignore","line":1,"symbol":"ignore/this/path","kind":"field","lang":"gitignore","code":"ignore/this/path"} {"repo":"ripgrep","file":"crates/ignore/tests/gitignore_skip_bom.rs","line":10,"symbol":"gitignore_skip_bom","kind":"function","lang":"rust","doc":"Skip a Byte-Order Mark (BOM) at the beginning of the file, matching Git's behavior. Ref: ","code":"fn gitignore_skip_bom() {\n let mut builder = GitignoreBuilder::new(\"ROOT\");\n let error = builder.add(IGNORE_FILE);\n assert!(error.is_none(), \"failed to open gitignore file\");\n let g = builder.build().unwrap();\n\n assert!(g.matched(\"ignore/this/path\", false).is_ignore());\n}"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":12,"symbol":"Index","kind":"type","lang":"rust","code":"pub struct Index {\n path: PathBuf,\n db: Handle,\n}"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":18,"symbol":"builder","kind":"function","lang":"rust","code":"pub fn builder() -> IndexBuilder {\n IndexBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":22,"symbol":"exists","kind":"function","lang":"rust","code":"pub fn exists(path: impl AsRef) -> bool {\n let path = path.as_ref();\n path.is_dir() && path.join(INDEX_FILE_NAME).is_file()\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":27,"symbol":"path","kind":"function","lang":"rust","code":"pub fn path(&self) -> &Path {\n &self.path\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":33,"symbol":"IndexBuilder","kind":"type","lang":"rust","code":"pub struct IndexBuilder {\n create: bool,\n write: bool,\n}"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":39,"symbol":"new","kind":"function","lang":"rust","code":"pub fn new() -> IndexBuilder {\n IndexBuilder::default()\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":43,"symbol":"build","kind":"function","lang":"rust","code":"pub fn build(&self, path: impl AsRef) -> anyhow::Result {\n let path = path.as_ref();\n if self.create {\n self.build_create(path)\n } else {\n self.build_open(path)\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":52,"symbol":"build_create","kind":"function","lang":"rust","code":"fn build_create(&self, path: &Path) -> anyhow::Result {\n if let Err(err) = std::fs::create_dir(path)\n && err.kind() != std::io::ErrorKind::AlreadyExists\n {\n return Err(err).with_context(|| {\n format!(\"{}: failed to create directory\", path.display())\n });\n }\n let path = path.join(INDEX_FILE_NAME);\n // TODO: Retry here if the database is already open.\n let db = Database::create(&path).with_context(|| {\n format!(\"{}: failed to create database\", path.display())\n })?;\n let index = Index { path, db: Handle::ReadWrite(db) };\n Ok(index)\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":69,"symbol":"build_open","kind":"function","lang":"rust","code":"fn build_open(&self, path: &Path) -> anyhow::Result {\n let path = path.join(INDEX_FILE_NAME);\n // TODO: Retry here if the database is already open.\n let db = if self.write {\n Handle::ReadWrite(Database::open(&path).with_context(|| {\n format!(\n \"{}: failed to open read-write database\",\n path.display()\n )\n })?)\n } else {\n Handle::ReadOnly(ReadOnlyDatabase::open(&path).with_context(\n || {\n format!(\n \"{}: failed to open read-only database\",\n path.display()\n )\n },\n )?)\n };\n let index = Index { path, db };\n Ok(index)\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":93,"symbol":"create","kind":"function","lang":"rust","code":"pub fn create(&mut self, yes: bool) -> &mut IndexBuilder {\n self.create = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":98,"symbol":"write","kind":"function","lang":"rust","code":"pub fn write(&mut self, yes: bool) -> &mut IndexBuilder {\n self.write = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":104,"symbol":"IndexDiscovery","kind":"type","lang":"rust","code":"pub struct IndexDiscovery {\n builder: IndexBuilder,\n cwd: Option,\n env_name: OsString,\n dir_name: OsString,\n}"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":112,"symbol":"new","kind":"function","lang":"rust","code":"pub fn new() -> IndexDiscovery {\n IndexDiscovery {\n builder: IndexBuilder::new(),\n cwd: None,\n env_name: \"RIPGREP_INDEX_PATH\".into(),\n dir_name: \".ripgrep\".into(),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":121,"symbol":"discover","kind":"function","lang":"rust","code":"pub fn discover(&self) -> anyhow::Result> {\n let cwd = match self.cwd.clone() {\n Some(cwd) => cwd,\n None => std::env::current_dir()\n .context(\"failed to get current working directory\")?,\n };\n anyhow::ensure!(\n cwd.is_absolute(),\n \"current working directory `{}` is not absolute\",\n cwd.display()\n );\n if let Some(env_path) = std::env::var_os(&self.env_name) {\n if !env_path.is_empty() {\n return Ok(Some(self.builder.build(env_path)?));\n }\n }\n for ancestor in cwd.ancestors() {\n let path = ancestor.join(&self.dir_name);\n // I guess this is subject to TOCTOU problems, but the underlying\n // embedded database should handle synchronization problems for us.\n if self.builder.create || Index::exists(&path) {\n return Ok(Some(self.builder.build(&path)?));\n }\n }\n Ok(None)\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":148,"symbol":"cwd","kind":"function","lang":"rust","code":"pub fn cwd(&mut self, cwd: impl AsRef) -> &mut IndexDiscovery {\n self.cwd = Some(cwd.as_ref().into());\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":153,"symbol":"env_name","kind":"function","lang":"rust","code":"pub fn env_name(\n &mut self,\n name: impl AsRef,\n ) -> &mut IndexDiscovery {\n self.env_name = name.as_ref().into();\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":161,"symbol":"dir_name","kind":"function","lang":"rust","code":"pub fn dir_name(\n &mut self,\n name: impl AsRef,\n ) -> &mut IndexDiscovery {\n self.dir_name = name.as_ref().into();\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":169,"symbol":"create","kind":"function","lang":"rust","code":"pub fn create(&mut self, yes: bool) -> &mut IndexDiscovery {\n self.builder.create(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":175,"symbol":"Handle","kind":"type","lang":"rust","code":"enum Handle {\n ReadWrite(Database),\n ReadOnly(ReadOnlyDatabase),\n}"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":181,"symbol":"begin_read","kind":"function","lang":"rust","code":"fn begin_read(\n &self,\n ) -> Result {\n use redb::ReadableDatabase;\n match self {\n Handle::ReadWrite(database) => database.begin_read(),\n Handle::ReadOnly(database) => database.begin_read(),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":191,"symbol":"read_write","kind":"function","lang":"rust","code":"fn read_write(&self) -> anyhow::Result<&Database> {\n match self {\n Handle::ReadWrite(database) => Ok(database),\n Handle::ReadOnly(_) => {\n anyhow::bail!(\"index was opened read-only\")\n }\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":200,"symbol":"read_write_mut","kind":"function","lang":"rust","code":"fn read_write_mut(&mut self) -> anyhow::Result<&mut Database> {\n match self {\n Handle::ReadWrite(database) => Ok(database),\n Handle::ReadOnly(_) => {\n anyhow::bail!(\"index was opened read-only\")\n }\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/index.rs","line":211,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n match *self {\n Handle::ReadWrite(_) => write!(f, \"\"),\n Handle::ReadOnly(_) => write!(f, \"\"),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":16,"symbol":"GramQuery","kind":"type","lang":"rust","code":"pub enum GramQuery {\n Literal(BString),\n And(Vec),\n Or(Vec),\n}"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":23,"symbol":"nothing","kind":"function","lang":"rust","code":"fn nothing() -> GramQuery {\n GramQuery::Or(vec![])\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":27,"symbol":"anything","kind":"function","lang":"rust","code":"fn anything() -> GramQuery {\n GramQuery::And(vec![])\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":31,"symbol":"is_nothing","kind":"function","lang":"rust","code":"fn is_nothing(&self) -> bool {\n match *self {\n GramQuery::Or(ref qs) => qs.is_empty(),\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":38,"symbol":"is_anything","kind":"function","lang":"rust","code":"fn is_anything(&self) -> bool {\n match *self {\n GramQuery::And(ref qs) => qs.is_empty(),\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":45,"symbol":"is_literal","kind":"function","lang":"rust","code":"fn is_literal(&self) -> bool {\n matches!(*self, GramQuery::Literal(..))\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":49,"symbol":"is_and","kind":"function","lang":"rust","code":"fn is_and(&self) -> bool {\n matches!(*self, GramQuery::And(..))\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":53,"symbol":"is_or","kind":"function","lang":"rust","code":"fn is_or(&self) -> bool {\n matches!(*self, GramQuery::Or(..))\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":57,"symbol":"unwrap","kind":"function","lang":"rust","code":"fn unwrap(self) -> GramQuery {\n match self {\n q @ GramQuery::Literal(_) => q,\n GramQuery::And(qs) => GramQuery::and(qs),\n GramQuery::Or(qs) => GramQuery::or(qs),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":65,"symbol":"unwrap_literal","kind":"function","lang":"rust","code":"fn unwrap_literal(self) -> BString {\n match self {\n GramQuery::Literal(lit) => lit,\n GramQuery::And(_) => panic!(\"expected literal, but got And\"),\n GramQuery::Or(_) => panic!(\"expected literal, but got Or\"),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":73,"symbol":"or","kind":"function","lang":"rust","code":"fn or(mut queries: Vec) -> GramQuery {\n queries.retain(|q| !q.is_nothing());\n\n if queries.iter().any(GramQuery::is_anything) {\n GramQuery::anything()\n } else if queries.len() == 1 {\n queries.pop().unwrap()\n } else if queries.iter().all(GramQuery::is_literal) {\n let set = LiteralSet::from_vec(\n queries.into_iter().map(GramQuery::unwrap_literal).collect(),\n );\n GramQuery::from_set_or(set)\n } else if queries.iter().any(GramQuery::is_or) {\n let mut flat = vec![];\n for q in queries {\n match q {\n GramQuery::Or(qs) => {\n flat.extend(qs);\n }\n q => flat.push(q),\n }\n }\n GramQuery::or(flat)\n } else {\n GramQuery::Or(queries)\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":101,"symbol":"and","kind":"function","lang":"rust","code":"fn and(mut queries: Vec) -> GramQuery {\n queries.retain(|q| !q.is_anything());\n\n if queries.iter().any(GramQuery::is_nothing) {\n GramQuery::nothing()\n } else if queries.len() == 1 {\n queries.pop().unwrap()\n } else if queries.iter().all(GramQuery::is_literal) {\n let set = LiteralSet::from_vec(\n queries.into_iter().map(GramQuery::unwrap_literal).collect(),\n );\n GramQuery::from_set_and(set)\n } else if queries.iter().any(GramQuery::is_and) {\n let mut flat = vec![];\n for q in queries {\n match q {\n GramQuery::And(qs) => {\n flat.extend(qs);\n }\n q => flat.push(q),\n }\n }\n GramQuery::and(flat)\n } else {\n GramQuery::And(queries)\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":129,"symbol":"from_set_or","kind":"function","lang":"rust","code":"fn from_set_or(mut set: LiteralSet) -> GramQuery {\n if set.is_empty() {\n GramQuery::anything()\n } else if set.len() == 1 {\n GramQuery::Literal(set.lits.pop().unwrap())\n } else {\n let lits: Vec<_> =\n set.lits.into_iter().map(GramQuery::Literal).collect();\n GramQuery::Or(lits)\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":141,"symbol":"from_set_and","kind":"function","lang":"rust","code":"fn from_set_and(mut set: LiteralSet) -> GramQuery {\n if set.is_empty() {\n GramQuery::anything()\n } else if set.len() == 1 {\n GramQuery::Literal(set.lits.pop().unwrap())\n } else {\n let lits: Vec<_> =\n set.lits.into_iter().map(GramQuery::Literal).collect();\n GramQuery::And(lits)\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":153,"symbol":"union","kind":"function","lang":"rust","code":"fn union(&mut self, q2: GramQuery) {\n use self::GramQuery::*;\n\n let (or, and) = (GramQuery::or, GramQuery::and);\n let q1 = mem::replace(self, GramQuery::nothing());\n match (q1, q2) {\n (Literal(lit1), Literal(lit2)) => {\n // let set = LiteralSet::from_vec(vec![lit1, lit2]);\n // *self = GramQuery::from_set_or(set);\n *self = or(vec![Literal(lit1), Literal(lit2)]);\n }\n (Literal(lit1), And(qs2)) => {\n *self = or(vec![Literal(lit1), and(qs2)]);\n }\n (Literal(lit1), Or(mut qs2)) => {\n qs2.push(Literal(lit1));\n *self = or(qs2);\n }\n (And(qs1), And(qs2)) => {\n if qs1.iter().all(GramQuery::is_literal)\n && qs2.iter().all(GramQuery::is_literal)\n {\n let (common, not1, not2) = factor(qs1, qs2);\n let mut disjuncts = vec![];\n if !not1.is_empty() {\n disjuncts.push(GramQuery::from_set_and(not1));\n }\n if !not2.is_empty() {\n "} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":205,"symbol":"intersect","kind":"function","lang":"rust","code":"fn intersect(&mut self, q2: GramQuery) {\n use self::GramQuery::*;\n\n let (or, and) = (GramQuery::or, GramQuery::and);\n let q1 = mem::replace(self, GramQuery::nothing()).unwrap();\n let q2 = q2.unwrap();\n match (q1, q2) {\n (Literal(lit1), Literal(lit2)) => {\n *self = and(vec![Literal(lit1), Literal(lit2)]);\n }\n (Literal(lit1), And(mut qs2)) => {\n qs2.push(Literal(lit1));\n *self = and(qs2);\n }\n (Literal(lit1), Or(qs2)) => {\n *self = and(vec![Literal(lit1), or(qs2)]);\n }\n (And(mut qs1), q2) => {\n qs1.push(q2);\n *self = and(qs1);\n }\n (Or(qs1), Or(qs2)) => {\n if qs1.iter().all(GramQuery::is_literal)\n && qs2.iter().all(GramQuery::is_literal)\n {\n let (common, not1, not2) = factor(qs1, qs2);\n let mut conjuncts = vec![];\n if !not1.is_empty() {\n conjuncts.push(GramQuery::from_set_or(not1));\n }\n if !not2.is_emp"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":256,"symbol":"and_ngrams","kind":"function","lang":"rust","code":"fn and_ngrams(&mut self, size: usize, set: &LiteralSet) {\n if set.min_len() < size {\n return;\n }\n let mut qor = GramQuery::nothing();\n for lit in &set.lits {\n if lit.len() < size {\n continue;\n }\n\n let mut set = LiteralSet::new();\n set.extend(ngrams(size, lit).map(BString::from));\n qor.union(GramQuery::from_set_and(set));\n }\n self.intersect(qor);\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":275,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n if f.alternate() {\n return match *self {\n GramQuery::Literal(ref lit) => {\n f.debug_tuple(\"Literal\").field(lit).finish()\n }\n GramQuery::And(ref qs) => {\n f.debug_tuple(\"And\").field(qs).finish()\n }\n GramQuery::Or(ref qs) => {\n f.debug_tuple(\"Or\").field(qs).finish()\n }\n };\n }\n\n match *self {\n GramQuery::Literal(ref lit) => {\n let x = format!(\"{:?}\", lit);\n write!(f, \"'{}'\", &x[1..x.len() - 1])\n }\n GramQuery::And(ref qs) => {\n let it = qs.iter().map(|q| {\n if q.is_literal() {\n format!(\"{:?}\", q)\n } else {\n format!(\"({:?})\", q)\n }\n });\n write!(f, \"{}\", it.collect::>().join(\" & \"))\n }\n GramQuery::Or(ref qs) => {\n let it = qs.iter().map(|q| {\n if q.is_literal() {"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":320,"symbol":"Analysis","kind":"type","lang":"rust","code":"pub struct Analysis {\n size: usize,\n query: GramQuery,\n exact: LiteralSet,\n prefix: LiteralSet,\n suffix: LiteralSet,\n}"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":329,"symbol":"exact","kind":"function","lang":"rust","code":"fn exact(size: usize, set: LiteralSet) -> Analysis {\n Analysis {\n size,\n query: GramQuery::anything(),\n exact: set,\n prefix: LiteralSet::new(),\n suffix: LiteralSet::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":339,"symbol":"anything","kind":"function","lang":"rust","code":"fn anything(size: usize) -> Analysis {\n Analysis {\n size,\n query: GramQuery::anything(),\n exact: LiteralSet::new(),\n prefix: LiteralSet::new(),\n suffix: LiteralSet::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":349,"symbol":"exact_one","kind":"function","lang":"rust","code":"fn exact_one(size: usize, string: BString) -> Analysis {\n Analysis {\n size,\n query: GramQuery::anything(),\n exact: LiteralSet::single(string),\n prefix: LiteralSet::new(),\n suffix: LiteralSet::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":359,"symbol":"empty_string","kind":"function","lang":"rust","code":"fn empty_string(size: usize) -> Analysis {\n Analysis::exact(size, LiteralSet::single(BString::from(\"\")))\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":363,"symbol":"max_len","kind":"function","lang":"rust","code":"fn max_len(&self) -> usize {\n cmp::max(\n self.exact.len(),\n cmp::max(self.prefix.len(), self.suffix.len()),\n )\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":370,"symbol":"is_exact","kind":"function","lang":"rust","code":"fn is_exact(&self) -> bool {\n !self.exact.is_empty()\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":374,"symbol":"make_inexact","kind":"function","lang":"rust","code":"fn make_inexact(&mut self) {\n if !self.is_exact() {\n return;\n }\n self.prefix = mem::replace(&mut self.exact, LiteralSet::new());\n self.suffix = self.prefix.clone();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":382,"symbol":"save_exact","kind":"function","lang":"rust","code":"fn save_exact(&mut self) {\n self.query.and_ngrams(self.size, &self.exact);\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":386,"symbol":"union","kind":"function","lang":"rust","code":"fn union(&mut self, mut o: Analysis) {\n if self.is_exact() && o.is_exact() {\n self.exact.union(o.exact);\n } else if self.is_exact() {\n self.save_exact();\n self.make_inexact();\n self.prefix.union(o.prefix);\n self.suffix.union(o.suffix);\n } else if o.is_exact() {\n o.save_exact();\n self.prefix.union(o.exact.clone());\n self.suffix.union(o.exact);\n } else {\n self.prefix.union(o.prefix);\n self.suffix.union(o.suffix);\n }\n self.query.union(o.query);\n self.simplify();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":406,"symbol":"concat","kind":"function","lang":"rust","code":"fn concat(&mut self, mut o: Analysis) {\n let inex_cross = if self.is_exact() && o.is_exact() {\n self.exact.cross(o.exact);\n None\n } else {\n let self_exact = self.is_exact();\n let o_exact = o.is_exact();\n self.make_inexact();\n o.make_inexact();\n\n let inex_cross = if !self_exact && !o_exact {\n let mut cross = self.suffix.clone();\n cross.cross(o.prefix.clone());\n Some(cross)\n } else {\n None\n };\n\n if self_exact {\n self.prefix.cross(o.prefix);\n } else if self.prefix.has_empty() {\n self.prefix.union(o.prefix);\n }\n if o_exact {\n self.suffix.cross(o.suffix);\n } else if self.suffix.has_empty() {\n self.suffix.union(o.suffix);\n } else {\n self.suffix = o.suffix;\n }\n inex_cross\n };\n self.query.intersect(o.query);\n if let Some(cross) = inex_cross {\n self.query.and_ngrams(self.size, &cross);\n }\n self.simplify();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":445,"symbol":"simplify","kind":"function","lang":"rust","code":"fn simplify(&mut self) {\n if self.is_exact() && self.exact.min_len() >= (self.size + 1) {\n self.save_exact();\n for lit in &self.exact.lits {\n if lit.len() < self.size {\n self.prefix.lits.push(lit.clone());\n self.suffix.lits.push(lit.clone());\n } else {\n self.prefix.lits.push(lit[..self.size - 1].into());\n self.suffix\n .lits\n .push(lit[lit.len() - (self.size - 1)..].into());\n }\n }\n self.exact.clear();\n self.prefix.canonicalize();\n self.suffix.canonicalize();\n }\n if !self.is_exact() {\n self.simplify_prefix();\n self.simplify_suffix();\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":469,"symbol":"finalize","kind":"function","lang":"rust","code":"fn finalize(&mut self) {\n if self.is_exact() && self.exact.min_len() >= self.size {\n self.save_exact();\n for lit in &self.exact.lits {\n if lit.len() < self.size {\n self.prefix.lits.push(lit.clone());\n self.suffix.lits.push(lit.clone());\n } else {\n self.prefix.lits.push(lit[..self.size - 1].into());\n self.suffix\n .lits\n .push(lit[lit.len() - (self.size - 1)..].into());\n }\n }\n self.exact.clear();\n self.prefix.canonicalize();\n self.suffix.canonicalize();\n }\n if !self.is_exact() {\n self.simplify_prefix();\n self.simplify_suffix();\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":493,"symbol":"simplify_prefix","kind":"function","lang":"rust","code":"fn simplify_prefix(&mut self) {\n self.query.and_ngrams(self.size, &self.prefix);\n self.prefix.retain_prefix(self.size - 1);\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":498,"symbol":"simplify_suffix","kind":"function","lang":"rust","code":"fn simplify_suffix(&mut self) {\n self.query.and_ngrams(self.size, &self.suffix);\n self.suffix.retain_suffix(self.size - 1);\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":505,"symbol":"LiteralSet","kind":"type","lang":"rust","code":"struct LiteralSet {\n lits: Vec,\n}"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":510,"symbol":"new","kind":"function","lang":"rust","code":"fn new() -> LiteralSet {\n LiteralSet { lits: vec![] }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":514,"symbol":"single","kind":"function","lang":"rust","code":"fn single(lit: BString) -> LiteralSet {\n LiteralSet { lits: vec![lit] }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":518,"symbol":"from_vec","kind":"function","lang":"rust","code":"fn from_vec(lits: Vec) -> LiteralSet {\n let mut set = LiteralSet { lits };\n set.canonicalize();\n set\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":524,"symbol":"clear","kind":"function","lang":"rust","code":"fn clear(&mut self) {\n self.lits.clear();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":528,"symbol":"retain_prefix","kind":"function","lang":"rust","code":"fn retain_prefix(&mut self, max: usize) {\n for lit in &mut self.lits {\n lit.truncate(max);\n }\n self.canonicalize();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":535,"symbol":"retain_suffix","kind":"function","lang":"rust","code":"fn retain_suffix(&mut self, max: usize) {\n for lit in &mut self.lits {\n if lit.len() <= max {\n continue;\n }\n let start = lit.len() - max;\n lit.drain(..start);\n }\n self.canonicalize();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":546,"symbol":"extend","kind":"function","lang":"rust","code":"fn extend>(&mut self, it: I) {\n self.lits.extend(it);\n self.canonicalize();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":551,"symbol":"canonicalize","kind":"function","lang":"rust","code":"fn canonicalize(&mut self) {\n self.lits.sort();\n self.lits.dedup();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":556,"symbol":"factor","kind":"function","lang":"rust","code":"fn factor(self, o: LiteralSet) -> (LiteralSet, LiteralSet, LiteralSet) {\n // TODO: Do this without cloning every literal.\n\n let (set1, set2) = (self.lits, o.lits);\n let (mut common, mut not1, mut not2) = (vec![], vec![], vec![]);\n\n let (mut i1, mut i2) = (0, 0);\n while i1 < set1.len() && i2 < set2.len() {\n if set1[i1] < set2[i2] {\n not1.push(set1[i1].clone());\n i1 += 1;\n } else if set2[i2] < set1[i1] {\n not2.push(set2[i2].clone());\n i2 += 1;\n } else {\n common.push(set1[i1].clone());\n i1 += 1;\n i2 += 1;\n }\n }\n while i1 < set1.len() {\n not1.push(set1[i1].clone());\n i1 += 1;\n }\n while i2 < set2.len() {\n not2.push(set2[i2].clone());\n i2 += 1;\n }\n (\n LiteralSet::from_vec(common),\n LiteralSet::from_vec(not1),\n LiteralSet::from_vec(not2),\n )\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":591,"symbol":"union","kind":"function","lang":"rust","code":"fn union(&mut self, o: LiteralSet) {\n self.lits.extend(o.lits);\n self.canonicalize();\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":596,"symbol":"cross","kind":"function","lang":"rust","code":"fn cross(&mut self, o: LiteralSet) {\n if o.is_empty() || o.has_only_empty() {\n return;\n }\n if self.is_empty() || self.has_only_empty() {\n *self = o;\n return;\n }\n\n let orig = mem::take(&mut self.lits);\n for selflit in &orig {\n for olit in &o.lits {\n let mut newlit = selflit.clone();\n newlit.push_str(olit);\n self.lits.push(newlit);\n }\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":615,"symbol":"is_empty","kind":"function","lang":"rust","code":"fn is_empty(&self) -> bool {\n self.lits.is_empty()\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":619,"symbol":"len","kind":"function","lang":"rust","code":"fn len(&self) -> usize {\n self.lits.len()\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":623,"symbol":"min_len","kind":"function","lang":"rust","code":"fn min_len(&self) -> usize {\n self.lits.iter().map(|x| x.len()).min().unwrap_or(0)\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":627,"symbol":"has_empty","kind":"function","lang":"rust","code":"fn has_empty(&self) -> bool {\n self.lits.first().is_some_and(|x| x.is_empty())\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":631,"symbol":"has_only_empty","kind":"function","lang":"rust","code":"fn has_only_empty(&self) -> bool {\n self.len() == 1 && self.has_empty()\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":637,"symbol":"GramQueryBuilder","kind":"type","lang":"rust","code":"pub struct GramQueryBuilder {\n ngram_size: usize,\n limit_len: usize,\n limit_class: usize,\n}"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":644,"symbol":"new","kind":"function","lang":"rust","code":"pub fn new() -> GramQueryBuilder {\n GramQueryBuilder { ngram_size: 3, limit_len: 250, limit_class: 10 }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":648,"symbol":"ngram_size","kind":"function","lang":"rust","code":"pub fn ngram_size(&mut self, size: usize) -> &mut GramQueryBuilder {\n // A size smaller than this doesn't make a ton of sense, particularly\n // given that it is currently measured in bytes, not codepoints (or\n // graphemes).\n assert!(size >= 2);\n self.ngram_size = size;\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":657,"symbol":"limit_len","kind":"function","lang":"rust","code":"pub fn limit_len(&mut self, len: usize) -> &mut GramQueryBuilder {\n self.limit_len = len;\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":662,"symbol":"limit_class","kind":"function","lang":"rust","code":"pub fn limit_class(&mut self, len: usize) -> &mut GramQueryBuilder {\n self.limit_class = len;\n self\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":667,"symbol":"build","kind":"function","lang":"rust","code":"pub fn build(&self, exp: &Hir) -> GramQuery {\n self.build_analysis(exp).query\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":671,"symbol":"build_analysis","kind":"function","lang":"rust","code":"fn build_analysis(&self, exp: &Hir) -> Analysis {\n let mut ana = self.b(exp);\n ana.finalize();\n ana\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":677,"symbol":"b","kind":"function","lang":"rust","code":"fn b(&self, exp: &Hir) -> Analysis {\n match *exp.kind() {\n HirKind::Empty | HirKind::Look(_) => {\n Analysis::empty_string(self.ngram_size)\n }\n HirKind::Literal(ref literal) => Analysis::exact_one(\n self.ngram_size,\n BString::from(literal.0.as_ref()),\n ),\n HirKind::Class(hir::Class::Unicode(ref cls)) => {\n if class_over_limit_unicode(cls, self.limit_class) {\n return Analysis::anything(self.ngram_size);\n }\n\n let mut set = LiteralSet::new();\n for r in cls.iter() {\n for cp in (r.start() as u32)..=(r.end() as u32) {\n let Some(ch) = char::from_u32(cp) else {\n continue;\n };\n set.lits.push(BString::from(ch.to_string()));\n }\n }\n set.canonicalize();\n Analysis::exact(self.ngram_size, set)\n }\n HirKind::Class(hir::Class::Bytes(ref cls)) => {\n if class_over_limit_bytes(cls, self.limit_class) {\n "} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":750,"symbol":"build_literal_or_hir","kind":"function","lang":"rust","code":"fn build_literal_or_hir(&self, or: LiteralOrHir) -> Analysis {\n match or {\n LiteralOrHir::Literal(string) => {\n Analysis::exact_one(self.ngram_size, string)\n }\n LiteralOrHir::Other(exp) => self.b(exp),\n }\n }"} {"repo":"ripgrep","file":"crates/index/src/literal.rs","line":761,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> GramQueryBuilder {\n GramQueryBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":14,"symbol":"interpolate","kind":"function","lang":"rust","doc":"The `append` function given is responsible for writing the replacement to the `dst` buffer. That is, it is called with the capture group index of a capture group reference and is expected to resolve the index to its corresponding matched text. If no such match exists, then `append` should not write anything to its given buffer.","code":"pub fn interpolate(\n mut replacement: &[u8],\n mut append: A,\n mut name_to_index: N,\n dst: &mut Vec,\n) where\n A: FnMut(usize, &mut Vec),\n N: FnMut(&str) -> Option,\n{\n while !replacement.is_empty() {\n match memchr(b'$', replacement) {\n None => break,\n Some(i) => {\n dst.extend(&replacement[..i]);\n replacement = &replacement[i..];\n }\n }\n if replacement.get(1).map_or(false, |&b| b == b'$') {\n dst.push(b'$');\n replacement = &replacement[2..];\n continue;\n }\n debug_assert!(!replacement.is_empty());\n let cap_ref = match find_cap_ref(replacement) {\n Some(cap_ref) => cap_ref,\n None => {\n dst.push(b'$');\n replacement = &replacement[1..];\n continue;\n }\n };\n replacement = &replacement[cap_ref.end..];\n match cap_ref.cap {\n Ref::Number(i) => append(i, dst),\n Ref::Named(name) => {\n if let Some(i) = name_to_index(name) {\n append(i, dst);\n }\n }\n "} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":64,"symbol":"CaptureRef","kind":"type","lang":"rust","doc":"`CaptureRef` represents a reference to a capture group inside some text. The reference is either a capture group name or a number. It is also tagged with the position in the text immediately proceeding the capture reference.","code":"struct CaptureRef<'a> {\n cap: Ref<'a>,\n end: usize,\n}"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":73,"symbol":"Ref","kind":"type","lang":"rust","doc":"A reference to a capture group in some text. e.g., `$2`, `$foo`, `${foo}`.","code":"enum Ref<'a> {\n Named(&'a str),\n Number(usize),\n}"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":80,"symbol":"from","kind":"function","lang":"rust","code":"fn from(x: &'a str) -> Ref<'a> {\n Ref::Named(x)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":87,"symbol":"from","kind":"function","lang":"rust","code":"fn from(x: usize) -> Ref<'static> {\n Ref::Number(x)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":97,"symbol":"find_cap_ref","kind":"function","lang":"rust","doc":"Parses a possible reference to a capture group name in the given text, starting at the beginning of `replacement`. If no such valid reference could be found, None is returned.","code":"fn find_cap_ref(replacement: &[u8]) -> Option> {\n let mut i = 0;\n if replacement.len() <= 1 || replacement[0] != b'$' {\n return None;\n }\n let mut brace = false;\n i += 1;\n if replacement[i] == b'{' {\n brace = true;\n i += 1;\n }\n let mut cap_end = i;\n while replacement.get(cap_end).map_or(false, is_valid_cap_letter) {\n cap_end += 1;\n }\n if cap_end == i {\n return None;\n }\n // We just verified that the range 0..cap_end is valid ASCII, so it must\n // therefore be valid UTF-8. If we really cared, we could avoid this UTF-8\n // check with an unchecked conversion or by parsing the number straight\n // from &[u8].\n let cap = std::str::from_utf8(&replacement[i..cap_end])\n .expect(\"valid UTF-8 capture name\");\n if brace {\n if !replacement.get(cap_end).map_or(false, |&b| b == b'}') {\n return None;\n }\n cap_end += 1;\n }\n Some(CaptureRef {\n cap: match cap.parse::() {\n Ok(i) => Ref::Number(i as usize),\n Err(_) => Ref::Named(cap),\n },\n end: cap_end,\n })\n}"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":138,"symbol":"is_valid_cap_letter","kind":"function","lang":"rust","doc":"Returns true if and only if the given byte is allowed in a capture name.","code":"fn is_valid_cap_letter(b: &u8) -> bool {\n match *b {\n b'0'..=b'9' | b'a'..=b'z' | b'A'..=b'Z' | b'_' => true,\n _ => false,\n }\n}"} {"repo":"ripgrep","file":"crates/matcher/src/interpolate.rs","line":185,"symbol":"interpolate_string","kind":"function","lang":"rust","doc":"A convenience routine for using interpolate's unwieldy but flexible API.","code":"fn interpolate_string(\n mut name_to_index: Vec<(&'static str, usize)>,\n caps: Vec<&'static str>,\n replacement: &str,\n ) -> String {\n name_to_index.sort_by_key(|x| x.0);\n\n let mut dst = vec![];\n interpolate(\n replacement.as_bytes(),\n |i, dst| {\n if let Some(&s) = caps.get(i) {\n dst.extend(s.as_bytes());\n }\n },\n |name| -> Option {\n name_to_index\n .binary_search_by_key(&name, |x| x.0)\n .ok()\n .map(|i| name_to_index[i].1)\n },\n &mut dst,\n );\n String::from_utf8(dst).unwrap()\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":69,"symbol":"Match","kind":"type","lang":"rust","doc":"use grep_matcher::Match; let m = Match::new(2, 5); let bytes = b\"abcdefghi\"; assert_eq!(b\"cde\", &bytes[m]); ```","code":"pub struct Match {\n start: usize,\n end: usize,\n}"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":81,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new match. # Panics This function panics if `start > end`.","code":"pub fn new(start: usize, end: usize) -> Match {\n assert!(start <= end);\n Match { start, end }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":88,"symbol":"zero","kind":"function","lang":"rust","doc":"Creates a zero width match at the given offset.","code":"pub fn zero(offset: usize) -> Match {\n Match { start: offset, end: offset }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":94,"symbol":"start","kind":"function","lang":"rust","doc":"Return the start offset of this match.","code":"pub fn start(&self) -> usize {\n self.start\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":100,"symbol":"end","kind":"function","lang":"rust","doc":"Return the end offset of this match.","code":"pub fn end(&self) -> usize {\n self.end\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":111,"symbol":"with_start","kind":"function","lang":"rust","doc":"Return a new match with the start offset replaced with the given value. # Panics This method panics if `start > self.end`.","code":"pub fn with_start(&self, start: usize) -> Match {\n assert!(start <= self.end, \"{} is not <= {}\", start, self.end);\n Match { start, ..*self }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":123,"symbol":"with_end","kind":"function","lang":"rust","doc":"Return a new match with the end offset replaced with the given value. # Panics This method panics if `self.start > end`.","code":"pub fn with_end(&self, end: usize) -> Match {\n assert!(self.start <= end, \"{} is not <= {}\", self.start, end);\n Match { end, ..*self }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":138,"symbol":"offset","kind":"function","lang":"rust","doc":"returns the resulting match. # Panics This panics if adding the given amount to either the start or end offset would result in an overflow.","code":"pub fn offset(&self, amount: usize) -> Match {\n Match {\n start: self.start.checked_add(amount).unwrap(),\n end: self.end.checked_add(amount).unwrap(),\n }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":147,"symbol":"len","kind":"function","lang":"rust","doc":"Returns the number of bytes in this match.","code":"pub fn len(&self) -> usize {\n self.end - self.start\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":153,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if and only if this match is empty.","code":"pub fn is_empty(&self) -> bool {\n self.len() == 0\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":162,"symbol":"index","kind":"function","lang":"rust","code":"fn index(&self, index: Match) -> &[u8] {\n &self[index.start..index.end]\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":169,"symbol":"index_mut","kind":"function","lang":"rust","code":"fn index_mut(&mut self, index: Match) -> &mut [u8] {\n &mut self[index.start..index.end]\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":178,"symbol":"index","kind":"function","lang":"rust","code":"fn index(&self, index: Match) -> &str {\n &self[index.start..index.end]\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":195,"symbol":"LineTerminator","kind":"type","lang":"rust","doc":"Generally, a line terminator is a single byte, specifically, `\\n`, on Unix-like systems. On Windows, a line terminator is `\\r\\n` (referred to as `CRLF` for `Carriage Return; Line Feed`). The default line terminator is `\\n` on all platforms.","code":"pub struct LineTerminator(LineTerminatorImp);"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":198,"symbol":"LineTerminatorImp","kind":"type","lang":"rust","code":"enum LineTerminatorImp {\n /// Any single byte representing a line terminator.\n Byte(u8),\n /// A line terminator represented by `\\r\\n`.\n ///\n /// When this option is used, consumers may generally treat a lone `\\n` as\n /// a line terminator in addition to `\\r\\n`.\n CRLF,\n}"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":211,"symbol":"byte","kind":"function","lang":"rust","doc":"Return a new single-byte line terminator. Any byte is valid.","code":"pub fn byte(byte: u8) -> LineTerminator {\n LineTerminator(LineTerminatorImp::Byte(byte))\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":220,"symbol":"crlf","kind":"function","lang":"rust","doc":"Return a new line terminator represented by `\\r\\n`. When this option is used, consumers may generally treat a lone `\\n` as a line terminator in addition to `\\r\\n`.","code":"pub fn crlf() -> LineTerminator {\n LineTerminator(LineTerminatorImp::CRLF)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":226,"symbol":"is_crlf","kind":"function","lang":"rust","doc":"Returns true if and only if this line terminator is CRLF.","code":"pub fn is_crlf(&self) -> bool {\n self.0 == LineTerminatorImp::CRLF\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":236,"symbol":"as_byte","kind":"function","lang":"rust","doc":"Returns this line terminator as a single byte. If the line terminator is CRLF, then this returns `\\n`. This is useful for routines that, for example, find line boundaries by treating `\\n` as a line terminator even when it isn't preceded by `\\r`.","code":"pub fn as_byte(&self) -> u8 {\n match self.0 {\n LineTerminatorImp::Byte(byte) => byte,\n LineTerminatorImp::CRLF => b'\\n',\n }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":250,"symbol":"as_bytes","kind":"function","lang":"rust","doc":"Returns this line terminator as a sequence of bytes. This returns a singleton sequence for all line terminators except for `CRLF`, in which case, it returns `\\r\\n`. The slice returned is guaranteed to have length at least `1`.","code":"pub fn as_bytes(&self) -> &[u8] {\n match self.0 {\n LineTerminatorImp::Byte(ref byte) => std::slice::from_ref(byte),\n LineTerminatorImp::CRLF => &[b'\\r', b'\\n'],\n }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":263,"symbol":"is_suffix","kind":"function","lang":"rust","doc":"Returns true if and only if the given slice ends with this line terminator. If this line terminator is `CRLF`, then this only checks whether the last byte is `\\n`.","code":"pub fn is_suffix(&self, slice: &[u8]) -> bool {\n slice.last().map_or(false, |&b| b == self.as_byte())\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":270,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> LineTerminator {\n LineTerminator::byte(b'\\n')\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":288,"symbol":"ByteSet","kind":"type","lang":"rust","doc":"may never match. For example, if a search is configured to possibly produce results that span multiple lines but a caller provided pattern can never match across multiple lines, then it may make sense to divert to more optimized line oriented routines that don't need to handle the multi-line match case.","code":"pub struct ByteSet(BitSet);"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":291,"symbol":"BitSet","kind":"type","lang":"rust","code":"struct BitSet([u64; 4]);"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":294,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n let mut fmtd = f.debug_set();\n for b in 0..=255 {\n if ByteSet(*self).contains(b) {\n fmtd.entry(&b);\n }\n }\n fmtd.finish()\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":308,"symbol":"empty","kind":"function","lang":"rust","doc":"Create an empty set of bytes.","code":"pub fn empty() -> ByteSet {\n ByteSet(BitSet([0; 4]))\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":315,"symbol":"full","kind":"function","lang":"rust","doc":"Create a full set of bytes such that every possible byte is in the set returned.","code":"pub fn full() -> ByteSet {\n ByteSet(BitSet([u64::MAX; 4]))\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":323,"symbol":"add","kind":"function","lang":"rust","doc":"Add a byte to this set. If the given byte already belongs to this set, then this is a no-op.","code":"pub fn add(&mut self, byte: u8) {\n let bucket = byte / 64;\n let bit = byte % 64;\n (self.0).0[usize::from(bucket)] |= 1 << bit;\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":331,"symbol":"add_all","kind":"function","lang":"rust","doc":"Add an inclusive range of bytes.","code":"pub fn add_all(&mut self, start: u8, end: u8) {\n for b in start..=end {\n self.add(b);\n }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":341,"symbol":"remove","kind":"function","lang":"rust","doc":"Remove a byte from this set. If the given byte is not in this set, then this is a no-op.","code":"pub fn remove(&mut self, byte: u8) {\n let bucket = byte / 64;\n let bit = byte % 64;\n (self.0).0[usize::from(bucket)] &= !(1 << bit);\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":349,"symbol":"remove_all","kind":"function","lang":"rust","doc":"Remove an inclusive range of bytes.","code":"pub fn remove_all(&mut self, start: u8, end: u8) {\n for b in start..=end {\n self.remove(b);\n }\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":357,"symbol":"contains","kind":"function","lang":"rust","doc":"Return true if and only if the given byte is in this set.","code":"pub fn contains(&self, byte: u8) -> bool {\n let bucket = byte / 64;\n let bit = byte % 64;\n (self.0).0[usize::from(bucket)] & (1 << bit) > 0\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":379,"symbol":"Captures","kind":"type","lang":"rust","doc":"maintain their specific in-memory representation. Note that this trait explicitly does not provide a way to construct a new capture value. Instead, it is the responsibility of a `Matcher` to build one, which might require knowledge of the matcher's internal implementation details.","code":"pub trait Captures {\n /// Return the total number of capturing groups. This includes capturing\n /// groups that have not matched anything.\n fn len(&self) -> usize;\n\n /// Return the capturing group match at the given index. If no match of\n /// that capturing group exists, then this returns `None`.\n ///\n /// When a matcher reports a match with capturing groups, then the first\n /// capturing group (at index `0`) must always correspond to the offsets\n /// for the overall match.\n fn get(&self, i: usize) -> Option;\n\n /// Return the overall match for the capture.\n ///\n /// This returns the match for index `0`. That is it is equivalent to\n /// `get(0).unwrap()`\n #[inline]\n fn as_match(&self) -> Match {\n self.get(0).unwrap()\n }\n\n /// Returns true if and only if these captures are empty. This occurs\n /// when `len` is `0`.\n ///\n /// Note that capturing groups that have non-zero length but otherwise\n /// contain no matching groups are *not* empty.\n #[inline]\n fn is_empty(&self) -> bool {\n self.len() == 0\n }\n\n /// Expands all instances of `$name` in `replacement` to the corresponding\n /// capt"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":382,"symbol":"len","kind":"function","lang":"rust","doc":"Return the total number of capturing groups. This includes capturing groups that have not matched anything.","code":"fn len(&self) -> usize;"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":390,"symbol":"get","kind":"function","lang":"rust","doc":"Return the capturing group match at the given index. If no match of that capturing group exists, then this returns `None`. When a matcher reports a match with capturing groups, then the first capturing group (at index `0`) must always correspond to the offsets for the overall match.","code":"fn get(&self, i: usize) -> Option;"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":397,"symbol":"as_match","kind":"function","lang":"rust","doc":"Return the overall match for the capture. This returns the match for index `0`. That is it is equivalent to `get(0).unwrap()`","code":"fn as_match(&self) -> Match {\n self.get(0).unwrap()\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":407,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if and only if these captures are empty. This occurs when `len` is `0`. Note that capturing groups that have non-zero length but otherwise contain no matching groups are *not* empty.","code":"fn is_empty(&self) -> bool {\n self.len() == 0\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":441,"symbol":"interpolate","kind":"function","lang":"rust","doc":"To write a literal `$` use `$$`. Note that the capture group match indices are resolved by slicing the given `haystack`. Generally, this means that `haystack` should be the same slice that was searched to get the current capture group matches.","code":"fn interpolate(\n &self,\n name_to_index: F,\n haystack: &[u8],\n replacement: &[u8],\n dst: &mut Vec,\n ) where\n F: FnMut(&str) -> Option,\n {\n interpolate(\n replacement,\n |i, dst| {\n if let Some(range) = self.get(i) {\n dst.extend(&haystack[range]);\n }\n },\n name_to_index,\n dst,\n )\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":468,"symbol":"NoCaptures","kind":"type","lang":"rust","doc":"NoCaptures provides an always-empty implementation of the `Captures` trait. This type is useful for implementations of `Matcher` that don't support capturing groups.","code":"pub struct NoCaptures(());"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":473,"symbol":"new","kind":"function","lang":"rust","doc":"Create an empty set of capturing groups.","code":"pub fn new() -> NoCaptures {\n NoCaptures(())\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":480,"symbol":"len","kind":"function","lang":"rust","code":"fn len(&self) -> usize {\n 0\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":485,"symbol":"get","kind":"function","lang":"rust","code":"fn get(&self, _: usize) -> Option {\n None\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":497,"symbol":"NoError","kind":"type","lang":"rust","doc":"NoError provides an error type for matchers that never produce errors. This error type implements the `std::error::Error` and `std::fmt::Display` traits for use in matcher implementations that can never produce errors. The `std::fmt::Debug` and `std::fmt::Display` impls for this type panics.","code":"pub struct NoError(());"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":500,"symbol":"description","kind":"function","lang":"rust","code":"fn description(&self) -> &str {\n \"no error\"\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":506,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, _: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n panic!(\"BUG for NoError: an impossible error occurred\")\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":512,"symbol":"from","kind":"function","lang":"rust","code":"fn from(_: NoError) -> std::io::Error {\n panic!(\"BUG for NoError: an impossible error occurred\")\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":519,"symbol":"LineMatchKind","kind":"type","lang":"rust","doc":"The type of match for a line oriented matcher.","code":"pub enum LineMatchKind {\n /// A position inside a line that is known to contain a match.\n ///\n /// This position can be anywhere in the line. It does not need to point\n /// at the location of the match.\n Confirmed(usize),\n /// A position inside a line that may contain a match, and must be searched\n /// for verification.\n ///\n /// This position can be anywhere in the line. It does not need to point\n /// at the location of the match.\n Candidate(usize),\n}"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":546,"symbol":"Matcher","kind":"type","lang":"rust","doc":"dictated by the documentation. Crucially, this includes `captures_at`. The rest of the methods on this trait provide default implementations on top of `find_at` and `new_captures`. It is not uncommon for implementations to be able to provide faster variants of some methods; in those cases, simply override the default implementation.","code":"pub trait Matcher {\n /// The concrete type of capturing groups used for this matcher.\n ///\n /// If this implementation does not support capturing groups, then set\n /// this to `NoCaptures`.\n type Captures: Captures;\n\n /// The error type used by this matcher.\n ///\n /// For matchers in which an error is not possible, they are encouraged to\n /// use the `NoError` type in this crate. In the future, when the \"never\"\n /// (spelled `!`) type is stabilized, then it should probably be used\n /// instead.\n type Error: std::fmt::Display;\n\n /// Returns the start and end byte range of the first match in `haystack`\n /// after `at`, where the byte offsets are relative to that start of\n /// `haystack` (and not `at`). If no match exists, then `None` is returned.\n ///\n /// The text encoding of `haystack` is not strictly specified. Matchers are\n /// advised to assume UTF-8, or at worst, some ASCII compatible encoding.\n ///\n /// The significance of the starting point is that it takes the surrounding\n /// context into consideration. For example, the `\\A` anchor can only\n /// match when `at == 0`.\n fn find_at(\n &self,\n hay"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":571,"symbol":"find_at","kind":"function","lang":"rust","doc":"The text encoding of `haystack` is not strictly specified. Matchers are advised to assume UTF-8, or at worst, some ASCII compatible encoding. The significance of the starting point is that it takes the surrounding context into consideration. For example, the `\\A` anchor can only match when `at == 0`.","code":"fn find_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, Self::Error>;"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":583,"symbol":"new_captures","kind":"function","lang":"rust","doc":"Creates an empty group of captures suitable for use with the capturing APIs of this trait. Implementations that don't support capturing groups should use the `NoCaptures` type and implement this method by calling `NoCaptures::new()`.","code":"fn new_captures(&self) -> Result;"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":597,"symbol":"capture_count","kind":"function","lang":"rust","doc":"If a matcher does not support capturing groups, then this should always return 0. By default, capturing groups are not supported, so this always returns 0.","code":"fn capture_count(&self) -> usize {\n 0\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":611,"symbol":"capture_index","kind":"function","lang":"rust","doc":"If the given capture group name maps to multiple indices, then it is not specified which one is returned. However, it is guaranteed that one of them is returned. By default, capturing groups are not supported, so this always returns `None`.","code":"fn capture_index(&self, _name: &str) -> Option {\n None\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":621,"symbol":"find","kind":"function","lang":"rust","doc":"Returns the start and end byte range of the first match in `haystack`. If no match exists, then `None` is returned. The text encoding of `haystack` is not strictly specified. Matchers are advised to assume UTF-8, or at worst, some ASCII compatible encoding.","code":"fn find(&self, haystack: &[u8]) -> Result, Self::Error> {\n self.find_at(haystack, 0)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":629,"symbol":"find_iter","kind":"function","lang":"rust","doc":"Executes the given function over successive non-overlapping matches in `haystack`. If no match exists, then the given function is never called. If the function returns `false`, then iteration stops.","code":"fn find_iter(\n &self,\n haystack: &[u8],\n matched: F,\n ) -> Result<(), Self::Error>\n where\n F: FnMut(Match) -> bool,\n {\n self.find_iter_at(haystack, 0, matched)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":648,"symbol":"find_iter_at","kind":"function","lang":"rust","doc":"in `haystack`. If no match exists, then the given function is never called. If the function returns `false`, then iteration stops. The significance of the starting point is that it takes the surrounding context into consideration. For example, the `\\A` anchor can only match when `at == 0`.","code":"fn find_iter_at(\n &self,\n haystack: &[u8],\n at: usize,\n mut matched: F,\n ) -> Result<(), Self::Error>\n where\n F: FnMut(Match) -> bool,\n {\n self.try_find_iter_at(haystack, at, |m| Ok(matched(m)))\n .map(|r: Result<(), ()>| r.unwrap())\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":669,"symbol":"try_find_iter","kind":"function","lang":"rust","doc":"in `haystack`. If no match exists, then the given function is never called. If the function returns `false`, then iteration stops. Similarly, if the function returns an error then iteration stops and the error is yielded. If an error occurs while executing the search, then it is converted to `E`.","code":"fn try_find_iter(\n &self,\n haystack: &[u8],\n matched: F,\n ) -> Result, Self::Error>\n where\n F: FnMut(Match) -> Result,\n {\n self.try_find_iter_at(haystack, 0, matched)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":692,"symbol":"try_find_iter_at","kind":"function","lang":"rust","doc":"then it is converted to `E`. The significance of the starting point is that it takes the surrounding context into consideration. For example, the `\\A` anchor can only match when `at == 0`.","code":"fn try_find_iter_at(\n &self,\n haystack: &[u8],\n at: usize,\n mut matched: F,\n ) -> Result, Self::Error>\n where\n F: FnMut(Match) -> Result,\n {\n let mut last_end = at;\n let mut last_match = None;\n\n loop {\n if last_end > haystack.len() {\n return Ok(Ok(()));\n }\n let m = match self.find_at(haystack, last_end)? {\n None => return Ok(Ok(())),\n Some(m) => m,\n };\n if m.start == m.end {\n // This is an empty match. To ensure we make progress, start\n // the next search at the smallest possible starting position\n // of the next match following this one.\n last_end = m.end + 1;\n // Don't accept empty matches immediately following a match.\n // Just move on to the next match.\n if Some(m.end) == last_match {\n continue;\n }\n } else {\n last_end = m.end;\n }\n last_match = Some(m.end);\n match matched(m) {\n O"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":740,"symbol":"captures","kind":"function","lang":"rust","doc":"Populates the first set of capture group matches from `haystack` into `caps`. If no match exists, then `false` is returned. The text encoding of `haystack` is not strictly specified. Matchers are advised to assume UTF-8, or at worst, some ASCII compatible encoding.","code":"fn captures(\n &self,\n haystack: &[u8],\n caps: &mut Self::Captures,\n ) -> Result {\n self.captures_at(haystack, 0, caps)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":753,"symbol":"captures_iter","kind":"function","lang":"rust","doc":"Executes the given function over successive non-overlapping matches in `haystack` with capture groups extracted from each match. If no match exists, then the given function is never called. If the function returns `false`, then iteration stops.","code":"fn captures_iter(\n &self,\n haystack: &[u8],\n caps: &mut Self::Captures,\n matched: F,\n ) -> Result<(), Self::Error>\n where\n F: FnMut(&Self::Captures) -> bool,\n {\n self.captures_iter_at(haystack, 0, caps, matched)\n }"} {"repo":"ripgrep","file":"crates/matcher/src/lib.rs","line":774,"symbol":"captures_iter_at","kind":"function","lang":"rust","doc":"match exists, then the given function is never called. If the function returns `false`, then iteration stops. The significance of the starting point is that it takes the surrounding context into consideration. For example, the `\\A` anchor can only match when `at == 0`.","code":"fn captures_iter_at(\n &self,\n haystack: &[u8],\n at: usize,\n caps: &mut Self::Captures,\n mut matched: F,\n ) -> Result<(), Self::Error>\n where\n F: FnMut(&Self::Captures) -> bool,\n {\n self.try_captures_iter_at(haystack, at, caps, |caps| Ok(matched(caps)))\n .map(|r: Result<(), ()>| r.unwrap())\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":8,"symbol":"matcher","kind":"function","lang":"rust","code":"fn matcher(pattern: &str) -> RegexMatcher {\n RegexMatcher::new(Regex::new(pattern).unwrap())\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":12,"symbol":"matcher_no_caps","kind":"function","lang":"rust","code":"fn matcher_no_caps(pattern: &str) -> RegexMatcherNoCaps {\n RegexMatcherNoCaps(Regex::new(pattern).unwrap())\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":16,"symbol":"m","kind":"function","lang":"rust","code":"fn m(start: usize, end: usize) -> Match {\n Match::new(start, end)\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":21,"symbol":"find","kind":"function","lang":"rust","code":"fn find() {\n let matcher = matcher(r\"(\\w+)\\s+(\\w+)\");\n assert_eq!(matcher.find(b\" homer simpson \").unwrap(), Some(m(1, 14)));\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":27,"symbol":"find_iter","kind":"function","lang":"rust","code":"fn find_iter() {\n let matcher = matcher(r\"(\\w+)\\s+(\\w+)\");\n let mut matches = vec![];\n matcher\n .find_iter(b\"aa bb cc dd\", |m| {\n matches.push(m);\n true\n })\n .unwrap();\n assert_eq!(matches, vec![m(0, 5), m(6, 11)]);\n\n // Test that find_iter respects short circuiting.\n matches.clear();\n matcher\n .find_iter(b\"aa bb cc dd\", |m| {\n matches.push(m);\n false\n })\n .unwrap();\n assert_eq!(matches, vec![m(0, 5)]);\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":50,"symbol":"try_find_iter","kind":"function","lang":"rust","code":"fn try_find_iter() {\n #[derive(Clone, Debug, Eq, PartialEq)]\n struct MyError;\n\n let matcher = matcher(r\"(\\w+)\\s+(\\w+)\");\n let mut matches = vec![];\n let err = matcher\n .try_find_iter(b\"aa bb cc dd\", |m| {\n if matches.is_empty() {\n matches.push(m);\n Ok(true)\n } else {\n Err(MyError)\n }\n })\n .unwrap()\n .unwrap_err();\n assert_eq!(matches, vec![m(0, 5)]);\n assert_eq!(err, MyError);\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":52,"symbol":"MyError","kind":"type","lang":"rust","code":"struct MyError;"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":72,"symbol":"shortest_match","kind":"function","lang":"rust","code":"fn shortest_match() {\n let matcher = matcher(r\"a+\");\n // This tests that the default impl isn't doing anything smart, and simply\n // defers to `find`.\n assert_eq!(matcher.shortest_match(b\"aaa\").unwrap(), Some(3));\n // The actual underlying regex is smarter.\n assert_eq!(matcher.re.shortest_match(b\"aaa\"), Some(1));\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":82,"symbol":"captures","kind":"function","lang":"rust","code":"fn captures() {\n let matcher = matcher(r\"(?P\\w+)\\s+(?P\\w+)\");\n assert_eq!(matcher.capture_count(), 3);\n assert_eq!(matcher.capture_index(\"a\"), Some(1));\n assert_eq!(matcher.capture_index(\"b\"), Some(2));\n assert_eq!(matcher.capture_index(\"nada\"), None);\n\n let mut caps = matcher.new_captures().unwrap();\n assert!(matcher.captures(b\" homer simpson \", &mut caps).unwrap());\n assert_eq!(caps.get(0), Some(m(1, 14)));\n assert_eq!(caps.get(1), Some(m(1, 6)));\n assert_eq!(caps.get(2), Some(m(7, 14)));\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":97,"symbol":"captures_iter","kind":"function","lang":"rust","code":"fn captures_iter() {\n let matcher = matcher(r\"(?P\\w+)\\s+(?P\\w+)\");\n let mut caps = matcher.new_captures().unwrap();\n let mut matches = vec![];\n matcher\n .captures_iter(b\"aa bb cc dd\", &mut caps, |caps| {\n matches.push(caps.get(0).unwrap());\n matches.push(caps.get(1).unwrap());\n matches.push(caps.get(2).unwrap());\n true\n })\n .unwrap();\n assert_eq!(\n matches,\n vec![m(0, 5), m(0, 2), m(3, 5), m(6, 11), m(6, 8), m(9, 11),]\n );\n\n // Test that captures_iter respects short circuiting.\n matches.clear();\n matcher\n .captures_iter(b\"aa bb cc dd\", &mut caps, |caps| {\n matches.push(caps.get(0).unwrap());\n matches.push(caps.get(1).unwrap());\n matches.push(caps.get(2).unwrap());\n false\n })\n .unwrap();\n assert_eq!(matches, vec![m(0, 5), m(0, 2), m(3, 5),]);\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":128,"symbol":"try_captures_iter","kind":"function","lang":"rust","code":"fn try_captures_iter() {\n #[derive(Clone, Debug, Eq, PartialEq)]\n struct MyError;\n\n let matcher = matcher(r\"(?P\\w+)\\s+(?P\\w+)\");\n let mut caps = matcher.new_captures().unwrap();\n let mut matches = vec![];\n let err = matcher\n .try_captures_iter(b\"aa bb cc dd\", &mut caps, |caps| {\n if matches.is_empty() {\n matches.push(caps.get(0).unwrap());\n matches.push(caps.get(1).unwrap());\n matches.push(caps.get(2).unwrap());\n Ok(true)\n } else {\n Err(MyError)\n }\n })\n .unwrap()\n .unwrap_err();\n assert_eq!(matches, vec![m(0, 5), m(0, 2), m(3, 5)]);\n assert_eq!(err, MyError);\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":130,"symbol":"MyError","kind":"type","lang":"rust","code":"struct MyError;"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":156,"symbol":"no_captures","kind":"function","lang":"rust","doc":"Test that our default impls for capturing are correct. Namely, when capturing isn't supported by the underlying matcher, then all of the various capturing related APIs fail fast.","code":"fn no_captures() {\n let matcher = matcher_no_caps(r\"(?P\\w+)\\s+(?P\\w+)\");\n assert_eq!(matcher.capture_count(), 0);\n assert_eq!(matcher.capture_index(\"a\"), None);\n assert_eq!(matcher.capture_index(\"b\"), None);\n assert_eq!(matcher.capture_index(\"nada\"), None);\n\n let mut caps = matcher.new_captures().unwrap();\n assert!(!matcher.captures(b\"homer simpson\", &mut caps).unwrap());\n\n let mut called = false;\n matcher\n .captures_iter(b\"homer simpson\", &mut caps, |_| {\n called = true;\n true\n })\n .unwrap();\n assert!(!called);\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":177,"symbol":"replace","kind":"function","lang":"rust","code":"fn replace() {\n let matcher = matcher(r\"(\\w+)\\s+(\\w+)\");\n let mut dst = vec![];\n matcher\n .replace(b\"aa bb cc dd\", &mut dst, |_, dst| {\n dst.push(b'z');\n true\n })\n .unwrap();\n assert_eq!(dst, b\"z z\");\n\n // Test that replacements respect short circuiting.\n dst.clear();\n matcher\n .replace(b\"aa bb cc dd\", &mut dst, |_, dst| {\n dst.push(b'z');\n false\n })\n .unwrap();\n assert_eq!(dst, b\"z cc dd\");\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/test_matcher.rs","line":200,"symbol":"replace_with_captures","kind":"function","lang":"rust","code":"fn replace_with_captures() {\n let matcher = matcher(r\"(\\w+)\\s+(\\w+)\");\n let haystack = b\"aa bb cc dd\";\n let mut caps = matcher.new_captures().unwrap();\n let mut dst = vec![];\n matcher\n .replace_with_captures(haystack, &mut caps, &mut dst, |caps, dst| {\n caps.interpolate(\n |name| matcher.capture_index(name),\n haystack,\n b\"$2 $1\",\n dst,\n );\n true\n })\n .unwrap();\n assert_eq!(dst, b\"bb aa dd cc\");\n\n // Test that replacements respect short circuiting.\n dst.clear();\n matcher\n .replace_with_captures(haystack, &mut caps, &mut dst, |caps, dst| {\n caps.interpolate(\n |name| matcher.capture_index(name),\n haystack,\n b\"$2 $1\",\n dst,\n );\n false\n })\n .unwrap();\n assert_eq!(dst, b\"bb aa cc dd\");\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":9,"symbol":"RegexMatcher","kind":"type","lang":"rust","code":"pub(crate) struct RegexMatcher {\n pub re: Regex,\n pub names: HashMap,\n}"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":15,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(re: Regex) -> RegexMatcher {\n let mut names = HashMap::new();\n for (i, optional_name) in re.capture_names().enumerate() {\n if let Some(name) = optional_name {\n names.insert(name.to_string(), i);\n }\n }\n RegexMatcher { re, names }\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":32,"symbol":"find_at","kind":"function","lang":"rust","code":"fn find_at(&self, haystack: &[u8], at: usize) -> Result> {\n Ok(self\n .re\n .find_at(haystack, at)\n .map(|m| Match::new(m.start(), m.end())))\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":39,"symbol":"new_captures","kind":"function","lang":"rust","code":"fn new_captures(&self) -> Result {\n Ok(RegexCaptures(self.re.capture_locations()))\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":43,"symbol":"captures_at","kind":"function","lang":"rust","code":"fn captures_at(\n &self,\n haystack: &[u8],\n at: usize,\n caps: &mut RegexCaptures,\n ) -> Result {\n Ok(self.re.captures_read_at(&mut caps.0, haystack, at).is_some())\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":52,"symbol":"capture_count","kind":"function","lang":"rust","code":"fn capture_count(&self) -> usize {\n self.re.captures_len()\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":56,"symbol":"capture_index","kind":"function","lang":"rust","code":"fn capture_index(&self, name: &str) -> Option {\n self.names.get(name).copied()\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":67,"symbol":"RegexMatcherNoCaps","kind":"type","lang":"rust","code":"pub(crate) struct RegexMatcherNoCaps(pub(crate) Regex);"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":73,"symbol":"find_at","kind":"function","lang":"rust","code":"fn find_at(&self, haystack: &[u8], at: usize) -> Result> {\n Ok(self\n .0\n .find_at(haystack, at)\n .map(|m| Match::new(m.start(), m.end())))\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":80,"symbol":"new_captures","kind":"function","lang":"rust","code":"fn new_captures(&self) -> Result {\n Ok(NoCaptures::new())\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":86,"symbol":"RegexCaptures","kind":"type","lang":"rust","code":"pub(crate) struct RegexCaptures(CaptureLocations);"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":89,"symbol":"len","kind":"function","lang":"rust","code":"fn len(&self) -> usize {\n self.0.len()\n }"} {"repo":"ripgrep","file":"crates/matcher/tests/util.rs","line":93,"symbol":"get","kind":"function","lang":"rust","code":"fn get(&self, i: usize) -> Option {\n self.0.pos(i).map(|(s, e)| Match::new(s, e))\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/error.rs","line":7,"symbol":"Error","kind":"type","lang":"rust","doc":"An error that can occur in this crate. Generally, this error corresponds to problems building a regular expression, whether it's in parsing, compilation or a problem with guaranteeing a configured optimization.","code":"pub struct Error {\n kind: ErrorKind,\n}"} {"repo":"ripgrep","file":"crates/pcre2/src/error.rs","line":12,"symbol":"regex","kind":"function","lang":"rust","code":"pub(crate) fn regex(err: E) -> Error {\n Error { kind: ErrorKind::Regex(err.to_string()) }\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/error.rs","line":17,"symbol":"kind","kind":"function","lang":"rust","doc":"Return the kind of this error.","code":"pub fn kind(&self) -> &ErrorKind {\n &self.kind\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/error.rs","line":25,"symbol":"ErrorKind","kind":"type","lang":"rust","doc":"The kind of an error that can occur.","code":"pub enum ErrorKind {\n /// An error that occurred as a result of parsing a regular expression.\n /// This can be a syntax error or an error that results from attempting to\n /// compile a regular expression that is too big.\n ///\n /// The string here is the underlying error converted to a string.\n Regex(String),\n}"} {"repo":"ripgrep","file":"crates/pcre2/src/error.rs","line":35,"symbol":"description","kind":"function","lang":"rust","code":"fn description(&self) -> &str {\n match self.kind {\n ErrorKind::Regex(_) => \"regex error\",\n }\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/error.rs","line":43,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match self.kind {\n ErrorKind::Regex(ref s) => write!(f, \"{}\", s),\n }\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":12,"symbol":"RegexMatcherBuilder","kind":"type","lang":"rust","doc":"A builder for configuring the compilation of a PCRE2 regex.","code":"pub struct RegexMatcherBuilder {\n builder: RegexBuilder,\n case_smart: bool,\n word: bool,\n fixed_strings: bool,\n whole_line: bool,\n}"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":22,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new matcher builder with a default configuration.","code":"pub fn new() -> RegexMatcherBuilder {\n RegexMatcherBuilder {\n builder: RegexBuilder::new(),\n case_smart: false,\n word: false,\n fixed_strings: false,\n whole_line: false,\n }\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":37,"symbol":"build","kind":"function","lang":"rust","doc":"Compile the given pattern into a PCRE matcher using the current configuration. If there was a problem compiling the pattern, then an error is returned.","code":"pub fn build(&self, pattern: &str) -> Result {\n self.build_many(&[pattern])\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":45,"symbol":"build_many","kind":"function","lang":"rust","doc":"Compile all of the given patterns into a single regex that matches when at least one of the patterns matches. If there was a problem building the regex, then an error is returned.","code":"pub fn build_many>(\n &self,\n patterns: &[P],\n ) -> Result {\n let mut builder = self.builder.clone();\n let mut pats = Vec::with_capacity(patterns.len());\n for p in patterns.iter() {\n pats.push(if self.fixed_strings {\n format!(\"(?:{})\", pcre2::escape(p.as_ref()))\n } else {\n format!(\"(?:{})\", p.as_ref())\n });\n }\n let mut singlepat = if patterns.is_empty() {\n // A way to spell a pattern that can never match anything.\n r\"[^\\S\\s]\".to_string()\n } else {\n pats.join(\"|\")\n };\n if self.case_smart && !has_uppercase_literal(&singlepat) {\n builder.caseless(true);\n }\n if self.whole_line {\n singlepat = format!(r\"(?m:^)(?:{})(?m:$)\", singlepat);\n } else if self.word {\n // We make this option exclusive with whole_line because when\n // whole_line is enabled, all matches necessary fall on word\n // boundaries. So this extra goop is strictly redundant.\n singlepat = format!(r\"(? &mut RegexMatcherBuilder {\n self.builder.caseless(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":115,"symbol":"case_smart","kind":"function","lang":"rust","doc":"uppercase according to Unicode. For example, `foo\\pL` has no uppercase literals but `Foo\\pL` does. Note that the implementation of this is not perfect. Namely, `\\p{Ll}` will prevent case insensitive matching even though it is part of a meta sequence. This bug will probably never be fixed.","code":"pub fn case_smart(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.case_smart = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":127,"symbol":"dotall","kind":"function","lang":"rust","doc":"When enabled, the `.` metacharacter in the pattern matches any character, include `\\n`. When disabled (the default), `.` will match any character except for `\\n`. This option corresponds to the `s` flag.","code":"pub fn dotall(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.dotall(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":135,"symbol":"extended","kind":"function","lang":"rust","doc":"Enable \"extended\" mode in the pattern, where whitespace is ignored. This option corresponds to the `x` flag.","code":"pub fn extended(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.extended(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":148,"symbol":"multi_line","kind":"function","lang":"rust","doc":"When enabled, the `^` and `$` anchors will match both at the beginning and end of a subject string, in addition to matching at the start of a line and the end of a line. When disabled, the `^` and `$` anchors will only match at the beginning and end of a subject string. This option corresponds to the `m` flag.","code":"pub fn multi_line(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.multi_line(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":160,"symbol":"crlf","kind":"function","lang":"rust","doc":"When enabled, anchors such as `^` and `$` will match any of the following as a line terminator: `\\r`, `\\n` or `\\r\\n`. This is disabled by default, in which case, only `\\n` is recognized as a line terminator.","code":"pub fn crlf(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.crlf(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":176,"symbol":"word","kind":"function","lang":"rust","doc":"non-word character. This option, in contrast, merely requires that one side match a non-word character. For example, `\\b-2\\b` will not match `foo -2 bar` since `-` is not a word character. However, `-2` with this `word` option enabled will match the `-2` in `foo -2 bar`.","code":"pub fn word(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.word = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":184,"symbol":"fixed_strings","kind":"function","lang":"rust","doc":"Whether the patterns should be treated as literal strings or not. When this is active, all characters, including ones that would normally be special regex meta characters, are matched literally.","code":"pub fn fixed_strings(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.fixed_strings = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":191,"symbol":"whole_line","kind":"function","lang":"rust","doc":"Whether each pattern should match the entire line or not. This is equivalent to surrounding the pattern with `(?m:^)` and `(?m:$)`.","code":"pub fn whole_line(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.whole_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":205,"symbol":"ucp","kind":"function","lang":"rust","doc":"`\\d`, `\\D`, `\\s`, `\\S`, `\\w`, `\\W`. When set, this implies UTF matching mode. It is not possible to enable Unicode matching mode without enabling UTF matching mode. This is disabled by default.","code":"pub fn ucp(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.ucp(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":225,"symbol":"utf","kind":"function","lang":"rust","doc":"will do a UTF-8 validation check, which can impact performance. The UTF-8 check can be disabled via the `disable_utf_check` option, but it is undefined behavior to enable UTF matching mode and search invalid UTF-8. This is disabled by default.","code":"pub fn utf(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.utf(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":245,"symbol":"disable_utf_check","kind":"function","lang":"rust","code":"pub fn disable_utf_check(&mut self) -> &mut RegexMatcherBuilder {\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":258,"symbol":"jit","kind":"function","lang":"rust","doc":"can increase the time it takes to compile a pattern. If the JIT isn't available or if JIT compilation returns an error, then regex compilation will fail with the corresponding error. This is disabled by default, and always overrides `jit_if_available`.","code":"pub fn jit(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.jit(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":273,"symbol":"jit_if_available","kind":"function","lang":"rust","doc":"If the JIT isn't available or if JIT compilation returns an error, then a debug message with the error will be emitted and the regex will otherwise silently fall back to non-JIT matching. This is disabled by default, and always overrides `jit`.","code":"pub fn jit_if_available(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.builder.jit_if_available(yes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":291,"symbol":"max_jit_stack_size","kind":"function","lang":"rust","doc":"When this is set, then a new JIT stack will be created with the given maximum size as its limit. Increasing the stack size can be useful for larger regular expressions. By default, this is set to `None`.","code":"pub fn max_jit_stack_size(\n &mut self,\n bytes: Option,\n ) -> &mut RegexMatcherBuilder {\n self.builder.max_jit_stack_size(bytes);\n self\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":302,"symbol":"RegexMatcher","kind":"type","lang":"rust","doc":"An implementation of the `Matcher` trait using PCRE2.","code":"pub struct RegexMatcher {\n regex: Regex,\n names: HashMap,\n}"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":310,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new matcher from the given pattern using the default configuration.","code":"pub fn new(pattern: &str) -> Result {\n RegexMatcherBuilder::new().build(pattern)\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":319,"symbol":"find_at","kind":"function","lang":"rust","code":"fn find_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, Error> {\n Ok(self\n .regex\n .find_at(haystack, at)\n .map_err(Error::regex)?\n .map(|m| Match::new(m.start(), m.end())))\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":331,"symbol":"new_captures","kind":"function","lang":"rust","code":"fn new_captures(&self) -> Result {\n Ok(RegexCaptures::new(self.regex.capture_locations()))\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":335,"symbol":"capture_count","kind":"function","lang":"rust","code":"fn capture_count(&self) -> usize {\n self.regex.captures_len()\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":339,"symbol":"capture_index","kind":"function","lang":"rust","code":"fn capture_index(&self, name: &str) -> Option {\n self.names.get(name).copied()\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":343,"symbol":"try_find_iter","kind":"function","lang":"rust","code":"fn try_find_iter(\n &self,\n haystack: &[u8],\n mut matched: F,\n ) -> Result, Error>\n where\n F: FnMut(Match) -> Result,\n {\n for result in self.regex.find_iter(haystack) {\n let m = result.map_err(Error::regex)?;\n match matched(Match::new(m.start(), m.end())) {\n Ok(true) => continue,\n Ok(false) => return Ok(Ok(())),\n Err(err) => return Ok(Err(err)),\n }\n }\n Ok(Ok(()))\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":362,"symbol":"captures_at","kind":"function","lang":"rust","code":"fn captures_at(\n &self,\n haystack: &[u8],\n at: usize,\n caps: &mut RegexCaptures,\n ) -> Result {\n Ok(self\n .regex\n .captures_read_at(&mut caps.locs, haystack, at)\n .map_err(Error::regex)?\n .is_some())\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":391,"symbol":"RegexCaptures","kind":"type","lang":"rust","doc":"For example, in the regex, `(?P\\w)|(?P\\W)`, only one of `foo` or `bar` will ever be set in any given match. In order to access a capture group by name, you'll need to first find the index of the group using the corresponding matcher's `capture_index` method, and then use that index with `RegexCaptures::get`.","code":"pub struct RegexCaptures {\n /// Where the locations are stored.\n locs: CaptureLocations,\n}"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":397,"symbol":"len","kind":"function","lang":"rust","code":"fn len(&self) -> usize {\n self.locs.len()\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":401,"symbol":"get","kind":"function","lang":"rust","code":"fn get(&self, i: usize) -> Option {\n self.locs.get(i).map(|(s, e)| Match::new(s, e))\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":407,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(locs: CaptureLocations) -> RegexCaptures {\n RegexCaptures { locs }\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":422,"symbol":"has_uppercase_literal","kind":"function","lang":"rust","doc":"things like '\\p{Ll}' and '\\p{Lu}' (which should be treated as explicitly cased), but PCRE doesn't expose enough details for that kind of analysis. For now, our 'good enough' solution is to simply perform a semi-naïve scan of the input pattern and ignore all characters following a '\\'. The This at least lets us support the most common cases, like 'foo\\w' and 'foo\\S', in an intuitive manner.","code":"fn has_uppercase_literal(pattern: &str) -> bool {\n let mut chars = pattern.chars();\n while let Some(c) = chars.next() {\n if c == '\\\\' {\n chars.next();\n } else if c.is_uppercase() {\n return true;\n }\n }\n false\n}"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":443,"symbol":"word","kind":"function","lang":"rust","doc":"Test that enabling word matches does the right thing and demonstrate the difference between it and surrounding the regex in `\\b`.","code":"fn word() {\n let matcher =\n RegexMatcherBuilder::new().word(true).build(r\"-2\").unwrap();\n assert!(matcher.is_match(b\"abc -2 foo\").unwrap());\n\n let matcher =\n RegexMatcherBuilder::new().word(false).build(r\"\\b-2\\b\").unwrap();\n assert!(!matcher.is_match(b\"abc -2 foo\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":455,"symbol":"line_terminator_crlf","kind":"function","lang":"rust","doc":"Test that enabling CRLF permits `$` to match at the end of a line.","code":"fn line_terminator_crlf() {\n // Test normal use of `$` with a `\\n` line terminator.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(matcher.is_match(b\"abc\\n\").unwrap());\n\n // Test that `$` doesn't match at `\\r\\n` boundary normally.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(!matcher.is_match(b\"abc\\r\\n\").unwrap());\n\n // Now check the CRLF handling.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .crlf(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(matcher.is_match(b\"abc\\r\\n\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":481,"symbol":"case_smart","kind":"function","lang":"rust","doc":"Test that smart case works.","code":"fn case_smart() {\n let matcher =\n RegexMatcherBuilder::new().case_smart(true).build(r\"abc\").unwrap();\n assert!(matcher.is_match(b\"ABC\").unwrap());\n\n let matcher =\n RegexMatcherBuilder::new().case_smart(true).build(r\"aBc\").unwrap();\n assert!(!matcher.is_match(b\"ABC\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":493,"symbol":"candidate_lines","kind":"function","lang":"rust","doc":"Test that finding candidate lines works as expected.","code":"fn candidate_lines() {\n fn is_confirmed(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Confirmed(_) => true,\n _ => false,\n }\n }\n\n let matcher = RegexMatcherBuilder::new().build(r\"\\wfoo\\s\").unwrap();\n let m = matcher.find_candidate_line(b\"afoo \").unwrap().unwrap();\n assert!(is_confirmed(m));\n }"} {"repo":"ripgrep","file":"crates/pcre2/src/matcher.rs","line":494,"symbol":"is_confirmed","kind":"function","lang":"rust","code":"fn is_confirmed(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Confirmed(_) => true,\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":10,"symbol":"default_color_specs","kind":"function","lang":"rust","doc":"This may change over time, but the color choices are meant to be fairly conservative that work across terminal themes. Additional color specifications can be added to the list returned. More recently added specifications override previously added specifications.","code":"pub fn default_color_specs() -> Vec {\n vec![\n #[cfg(unix)]\n \"path:fg:magenta\".parse().unwrap(),\n #[cfg(windows)]\n \"path:fg:cyan\".parse().unwrap(),\n \"line:fg:green\".parse().unwrap(),\n \"match:fg:red\".parse().unwrap(),\n \"match:style:bold\".parse().unwrap(),\n ]\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":24,"symbol":"ColorError","kind":"type","lang":"rust","doc":"An error that can occur when parsing color specifications.","code":"pub enum ColorError {\n /// This occurs when an unrecognized output type is used.\n UnrecognizedOutType(String),\n /// This occurs when an unrecognized spec type is used.\n UnrecognizedSpecType(String),\n /// This occurs when an unrecognized color name is used.\n UnrecognizedColor(String, String),\n /// This occurs when an unrecognized style attribute is used.\n UnrecognizedStyle(String),\n /// This occurs when the format of a color specification is invalid.\n InvalidFormat(String),\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":40,"symbol":"from_parse_error","kind":"function","lang":"rust","code":"fn from_parse_error(err: ParseColorError) -> ColorError {\n ColorError::UnrecognizedColor(\n err.invalid().to_string(),\n err.to_string(),\n )\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":49,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match *self {\n ColorError::UnrecognizedOutType(ref name) => write!(\n f,\n \"unrecognized output type '{}'. Choose from: \\\n path, line, column, match, highlight.\",\n name,\n ),\n ColorError::UnrecognizedSpecType(ref name) => write!(\n f,\n \"unrecognized spec type '{}'. Choose from: \\\n fg, bg, style, none.\",\n name,\n ),\n ColorError::UnrecognizedColor(_, ref msg) => write!(f, \"{}\", msg),\n ColorError::UnrecognizedStyle(ref name) => write!(\n f,\n \"unrecognized style attribute '{}'. Choose from: \\\n nobold, bold, nointense, intense, nounderline, \\\n underline, noitalic, italic.\",\n name,\n ),\n ColorError::InvalidFormat(ref original) => write!(\n f,\n \"invalid color spec format: '{}'. Valid format is \\\n '(path|line|column|match|highlight):(fg|bg|style):(value)'.\",\n original,\n "} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":88,"symbol":"ColorSpecs","kind":"type","lang":"rust","doc":"A merged set of color specifications. This set of color specifications represents the various color types that are supported by the printers in this crate. A set of color specifications can be created from a sequence of [`UserColorSpec`]s.","code":"pub struct ColorSpecs {\n path: ColorSpec,\n line: ColorSpec,\n column: ColorSpec,\n matched: ColorSpec,\n highlight: ColorSpec,\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":152,"symbol":"UserColorSpec","kind":"type","lang":"rust","doc":"let spec2 = user_spec2.to_color_spec(); assert_eq!(spec1.fg(), Some(&Color::Blue)); assert_eq!(spec2.bg(), Some(&Color::Rgb(0xFF, 0x7F, 0x00))); # } ```","code":"pub struct UserColorSpec {\n ty: OutType,\n value: SpecValue,\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":162,"symbol":"to_color_spec","kind":"function","lang":"rust","doc":"Convert this user provided color specification to a specification that can be used with `termcolor`. This drops the type of this specification (where the type indicates where the color is applied in the standard printer, e.g., to the file path or the line numbers, etc.).","code":"pub fn to_color_spec(&self) -> ColorSpec {\n let mut spec = ColorSpec::default();\n self.value.merge_into(&mut spec);\n spec\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":171,"symbol":"SpecValue","kind":"type","lang":"rust","doc":"The actual value given by the specification.","code":"enum SpecValue {\n None,\n Fg(Color),\n Bg(Color),\n Style(Style),\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":180,"symbol":"OutType","kind":"type","lang":"rust","doc":"The set of configurable portions of ripgrep's output.","code":"enum OutType {\n Path,\n Line,\n Column,\n Match,\n Highlight,\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":190,"symbol":"SpecType","kind":"type","lang":"rust","doc":"The specification type.","code":"enum SpecType {\n Fg,\n Bg,\n Style,\n None,\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":199,"symbol":"Style","kind":"type","lang":"rust","doc":"The set of available styles for use in the terminal.","code":"enum Style {\n Bold,\n NoBold,\n Intense,\n NoIntense,\n Underline,\n NoUnderline,\n Italic,\n NoItalic,\n}"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":213,"symbol":"new","kind":"function","lang":"rust","doc":"Create color specifications from a list of user supplied specifications.","code":"pub fn new(specs: &[UserColorSpec]) -> ColorSpecs {\n let mut merged = ColorSpecs::default();\n for spec in specs {\n match spec.ty {\n OutType::Path => spec.merge_into(&mut merged.path),\n OutType::Line => spec.merge_into(&mut merged.line),\n OutType::Column => spec.merge_into(&mut merged.column),\n OutType::Match => spec.merge_into(&mut merged.matched),\n OutType::Highlight => spec.merge_into(&mut merged.highlight),\n }\n }\n merged\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":232,"symbol":"default_with_color","kind":"function","lang":"rust","doc":"Create a default set of specifications that have color. This is distinct from `ColorSpecs`'s `Default` implementation in that this provides a set of default color choices, where as the `Default` implementation provides no color choices.","code":"pub fn default_with_color() -> ColorSpecs {\n ColorSpecs::new(&default_color_specs())\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":237,"symbol":"path","kind":"function","lang":"rust","doc":"Return the color specification for coloring file paths.","code":"pub fn path(&self) -> &ColorSpec {\n &self.path\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":242,"symbol":"line","kind":"function","lang":"rust","doc":"Return the color specification for coloring line numbers.","code":"pub fn line(&self) -> &ColorSpec {\n &self.line\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":247,"symbol":"column","kind":"function","lang":"rust","doc":"Return the color specification for coloring column numbers.","code":"pub fn column(&self) -> &ColorSpec {\n &self.column\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":252,"symbol":"matched","kind":"function","lang":"rust","doc":"Return the color specification for coloring matched text.","code":"pub fn matched(&self) -> &ColorSpec {\n &self.matched\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":258,"symbol":"highlight","kind":"function","lang":"rust","doc":"Return the color specification for coloring entire line if there is a matched text.","code":"pub fn highlight(&self) -> &ColorSpec {\n &self.highlight\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":265,"symbol":"merge_into","kind":"function","lang":"rust","doc":"Merge this spec into the given color specification.","code":"fn merge_into(&self, cspec: &mut ColorSpec) {\n self.value.merge_into(cspec);\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":272,"symbol":"merge_into","kind":"function","lang":"rust","doc":"Merge this spec value into the given color specification.","code":"fn merge_into(&self, cspec: &mut ColorSpec) {\n match *self {\n SpecValue::None => cspec.clear(),\n SpecValue::Fg(ref color) => {\n cspec.set_fg(Some(color.clone()));\n }\n SpecValue::Bg(ref color) => {\n cspec.set_bg(Some(color.clone()));\n }\n SpecValue::Style(ref style) => match *style {\n Style::Bold => {\n cspec.set_bold(true);\n }\n Style::NoBold => {\n cspec.set_bold(false);\n }\n Style::Intense => {\n cspec.set_intense(true);\n }\n Style::NoIntense => {\n cspec.set_intense(false);\n }\n Style::Underline => {\n cspec.set_underline(true);\n }\n Style::NoUnderline => {\n cspec.set_underline(false);\n }\n Style::Italic => {\n cspec.set_italic(true);\n }\n Style::NoItalic => {\n cspec.set_italic(false);\n }\n },\n "} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":314,"symbol":"from_str","kind":"function","lang":"rust","code":"fn from_str(s: &str) -> Result {\n let pieces: Vec<&str> = s.split(':').collect();\n if pieces.len() <= 1 || pieces.len() > 3 {\n return Err(ColorError::InvalidFormat(s.to_string()));\n }\n let otype: OutType = pieces[0].parse()?;\n match pieces[1].parse()? {\n SpecType::None => {\n Ok(UserColorSpec { ty: otype, value: SpecValue::None })\n }\n SpecType::Style => {\n if pieces.len() < 3 {\n return Err(ColorError::InvalidFormat(s.to_string()));\n }\n let style: Style = pieces[2].parse()?;\n Ok(UserColorSpec { ty: otype, value: SpecValue::Style(style) })\n }\n SpecType::Fg => {\n if pieces.len() < 3 {\n return Err(ColorError::InvalidFormat(s.to_string()));\n }\n let color: Color =\n pieces[2].parse().map_err(ColorError::from_parse_error)?;\n Ok(UserColorSpec { ty: otype, value: SpecValue::Fg(color) })\n }\n SpecType::Bg => {\n if pieces.len() < 3 {\n "} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":354,"symbol":"from_str","kind":"function","lang":"rust","code":"fn from_str(s: &str) -> Result {\n match &*s.to_lowercase() {\n \"path\" => Ok(OutType::Path),\n \"line\" => Ok(OutType::Line),\n \"column\" => Ok(OutType::Column),\n \"match\" => Ok(OutType::Match),\n \"highlight\" => Ok(OutType::Highlight),\n _ => Err(ColorError::UnrecognizedOutType(s.to_string())),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":369,"symbol":"from_str","kind":"function","lang":"rust","code":"fn from_str(s: &str) -> Result {\n match &*s.to_lowercase() {\n \"fg\" => Ok(SpecType::Fg),\n \"bg\" => Ok(SpecType::Bg),\n \"style\" => Ok(SpecType::Style),\n \"none\" => Ok(SpecType::None),\n _ => Err(ColorError::UnrecognizedSpecType(s.to_string())),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/color.rs","line":383,"symbol":"from_str","kind":"function","lang":"rust","code":"fn from_str(s: &str) -> Result {\n match &*s.to_lowercase() {\n \"bold\" => Ok(Style::Bold),\n \"nobold\" => Ok(Style::NoBold),\n \"intense\" => Ok(Style::Intense),\n \"nointense\" => Ok(Style::NoIntense),\n \"underline\" => Ok(Style::Underline),\n \"nounderline\" => Ok(Style::NoUnderline),\n \"italic\" => Ok(Style::Italic),\n \"noitalic\" => Ok(Style::NoItalic),\n _ => Err(ColorError::UnrecognizedStyle(s.to_string())),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":8,"symbol":"CounterWriter","kind":"type","lang":"rust","doc":"A writer that counts the number of bytes that have been successfully written.","code":"pub(crate) struct CounterWriter {\n wtr: W,\n count: u64,\n total_count: u64,\n}"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":15,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(wtr: W) -> CounterWriter {\n CounterWriter { wtr, count: 0, total_count: 0 }\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":24,"symbol":"count","kind":"function","lang":"rust","doc":"Returns the total number of bytes written since construction or the last time `reset` was called.","code":"pub(crate) fn count(&self) -> u64 {\n self.count\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":30,"symbol":"total_count","kind":"function","lang":"rust","doc":"Returns the total number of bytes written since construction.","code":"pub(crate) fn total_count(&self) -> u64 {\n self.total_count + self.count\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":36,"symbol":"reset_count","kind":"function","lang":"rust","doc":"Resets the number of bytes written to `0`.","code":"pub(crate) fn reset_count(&mut self) {\n self.total_count += self.count;\n self.count = 0;\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":42,"symbol":"get_mut","kind":"function","lang":"rust","code":"pub(crate) fn get_mut(&mut self) -> &mut W {\n &mut self.wtr\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":47,"symbol":"into_inner","kind":"function","lang":"rust","code":"pub(crate) fn into_inner(self) -> W {\n self.wtr\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":55,"symbol":"write","kind":"function","lang":"rust","doc":"A high match count ad hoc benchmark flagged this as a hot spot.","code":"fn write(&mut self, buf: &[u8]) -> Result {\n let n = self.wtr.write(buf)?;\n self.count += n as u64;\n Ok(n)\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":62,"symbol":"flush","kind":"function","lang":"rust","code":"fn flush(&mut self) -> Result<(), io::Error> {\n self.wtr.flush()\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":69,"symbol":"supports_color","kind":"function","lang":"rust","code":"fn supports_color(&self) -> bool {\n self.wtr.supports_color()\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":74,"symbol":"supports_hyperlinks","kind":"function","lang":"rust","code":"fn supports_hyperlinks(&self) -> bool {\n self.wtr.supports_hyperlinks()\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":79,"symbol":"set_color","kind":"function","lang":"rust","code":"fn set_color(&mut self, spec: &ColorSpec) -> io::Result<()> {\n self.wtr.set_color(spec)\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":84,"symbol":"set_hyperlink","kind":"function","lang":"rust","code":"fn set_hyperlink(&mut self, link: &HyperlinkSpec) -> io::Result<()> {\n self.wtr.set_hyperlink(link)\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":89,"symbol":"reset","kind":"function","lang":"rust","code":"fn reset(&mut self) -> io::Result<()> {\n self.wtr.reset()\n }"} {"repo":"ripgrep","file":"crates/printer/src/counter.rs","line":94,"symbol":"is_synchronous","kind":"function","lang":"rust","code":"fn is_synchronous(&self) -> bool {\n self.wtr.is_synchronous()\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/aliases.rs","line":71,"symbol":"alias","kind":"function","lang":"rust","doc":"Creates a [`HyperlinkAlias`].","code":"const fn alias(\n name: &'static str,\n description: &'static str,\n format: &'static str,\n) -> HyperlinkAlias {\n HyperlinkAlias { name, description, format, display_priority: None }\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/aliases.rs","line":80,"symbol":"prioritized_alias","kind":"function","lang":"rust","doc":"Creates a [`HyperlinkAlias`] with a display priority.","code":"const fn prioritized_alias(\n priority: i16,\n name: &'static str,\n description: &'static str,\n format: &'static str,\n) -> HyperlinkAlias {\n HyperlinkAlias {\n name,\n description,\n format,\n display_priority: Some(priority),\n }\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":25,"symbol":"HyperlinkConfig","kind":"type","lang":"rust","doc":"variables. The specific subset includes variables that are intended to be invariant throughout the lifetime of a process, such as a machine's hostname. A hyperlink configuration can be provided to printer builders such as [`StandardBuilder::hyperlink`](crate::StandardBuilder::hyperlink).","code":"pub struct HyperlinkConfig(Arc);"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":28,"symbol":"HyperlinkConfigInner","kind":"type","lang":"rust","code":"struct HyperlinkConfigInner {\n env: HyperlinkEnvironment,\n format: HyperlinkFormat,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":35,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new configuration from an environment and a format.","code":"pub fn new(\n env: HyperlinkEnvironment,\n format: HyperlinkFormat,\n ) -> HyperlinkConfig {\n HyperlinkConfig(Arc::new(HyperlinkConfigInner { env, format }))\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":43,"symbol":"environment","kind":"function","lang":"rust","doc":"Returns the hyperlink environment in this configuration.","code":"pub(crate) fn environment(&self) -> &HyperlinkEnvironment {\n &self.0.env\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":48,"symbol":"format","kind":"function","lang":"rust","doc":"Returns the hyperlink format in this configuration.","code":"pub(crate) fn format(&self) -> &HyperlinkFormat {\n &self.0.format\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":71,"symbol":"HyperlinkFormat","kind":"type","lang":"rust","doc":"let fmt = \"vscode\".parse::()?; assert_eq!(fmt.to_string(), \"vscode://file{path}:{line}:{column}\"); # Ok::<(), Box>(()) ```","code":"pub struct HyperlinkFormat {\n parts: Vec,\n is_line_dependent: bool,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":78,"symbol":"empty","kind":"function","lang":"rust","doc":"Creates an empty hyperlink format.","code":"pub fn empty() -> HyperlinkFormat {\n HyperlinkFormat::default()\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":83,"symbol":"is_empty","kind":"function","lang":"rust","doc":"Returns true if this format is empty.","code":"pub fn is_empty(&self) -> bool {\n self.parts.is_empty()\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":89,"symbol":"into_config","kind":"function","lang":"rust","doc":"Creates a [`HyperlinkConfig`] from this format and the environment given.","code":"pub fn into_config(self, env: HyperlinkEnvironment) -> HyperlinkConfig {\n HyperlinkConfig::new(env, self)\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":94,"symbol":"is_line_dependent","kind":"function","lang":"rust","doc":"Returns true if the format can produce line-dependent hyperlinks.","code":"pub(crate) fn is_line_dependent(&self) -> bool {\n self.is_line_dependent\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":102,"symbol":"from_str","kind":"function","lang":"rust","code":"fn from_str(s: &str) -> Result {\n use self::HyperlinkFormatErrorKind::*;\n\n #[derive(Debug)]\n enum State {\n Verbatim,\n VerbatimCloseVariable,\n OpenVariable,\n InVariable,\n }\n\n let mut builder = FormatBuilder::new();\n let input = match HyperlinkAlias::find(s) {\n Some(alias) => alias.format(),\n None => s,\n };\n let mut name = String::new();\n let mut state = State::Verbatim;\n let err = |kind| HyperlinkFormatError { kind };\n for ch in input.chars() {\n state = match state {\n State::Verbatim => {\n if ch == '{' {\n State::OpenVariable\n } else if ch == '}' {\n State::VerbatimCloseVariable\n } else {\n builder.append_char(ch);\n State::Verbatim\n }\n }\n State::VerbatimCloseVariable => {\n if ch == '}' {\n builder.append_char('}');\n State::V"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":106,"symbol":"State","kind":"type","lang":"rust","code":"enum State {\n Verbatim,\n VerbatimCloseVariable,\n OpenVariable,\n InVariable,\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":178,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n for part in self.parts.iter() {\n part.fmt(f)?;\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":191,"symbol":"HyperlinkAlias","kind":"type","lang":"rust","doc":"An alias for a hyperlink format. Hyperlink aliases are built-in formats, therefore they hold static values. Some of their features are usable in const blocks.","code":"pub struct HyperlinkAlias {\n name: &'static str,\n description: &'static str,\n format: &'static str,\n display_priority: Option,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":200,"symbol":"name","kind":"function","lang":"rust","doc":"Returns the name of the alias.","code":"pub const fn name(&self) -> &str {\n self.name\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":205,"symbol":"description","kind":"function","lang":"rust","doc":"Returns a very short description of this hyperlink alias.","code":"pub const fn description(&self) -> &str {\n self.description\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":223,"symbol":"display_priority","kind":"function","lang":"rust","doc":"A lower display priority implies the alias should be shown before aliases with a higher (or absent) display priority. Callers cannot rely on any specific display priority value to remain stable across semver compatible releases of this crate.","code":"pub const fn display_priority(&self) -> Option {\n self.display_priority\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":228,"symbol":"format","kind":"function","lang":"rust","doc":"Returns the format string of the alias.","code":"const fn format(&self) -> &'static str {\n self.format\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":235,"symbol":"find","kind":"function","lang":"rust","doc":"Looks for the hyperlink alias defined by the given name. If one does not exist, `None` is returned.","code":"fn find(name: &str) -> Option<&HyperlinkAlias> {\n HYPERLINK_PATTERN_ALIASES\n .binary_search_by_key(&name, |alias| alias.name())\n .map(|i| &HYPERLINK_PATTERN_ALIASES[i])\n .ok()\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":251,"symbol":"HyperlinkEnvironment","kind":"type","lang":"rust","doc":"This environment permits setting the values of variables used in hyperlink interpolation that are not expected to change for the lifetime of a program. That is, these values are invariant. Currently, this includes the hostname and a WSL distro prefix.","code":"pub struct HyperlinkEnvironment {\n host: Option,\n wsl_prefix: Option,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":258,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new empty hyperlink environment.","code":"pub fn new() -> HyperlinkEnvironment {\n HyperlinkEnvironment::default()\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":267,"symbol":"host","kind":"function","lang":"rust","doc":"Set the `{host}` variable, which fills in any hostname components of a hyperlink. One can get the hostname in the current environment via the `hostname` function in the `grep-cli` crate.","code":"pub fn host(&mut self, host: Option) -> &mut HyperlinkEnvironment {\n self.host = host;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":275,"symbol":"wsl_prefix","kind":"function","lang":"rust","doc":"Set the `{wslprefix}` variable, which contains the WSL distro prefix. An example value is `wsl$/Ubuntu`. The distro name can typically be discovered from the `WSL_DISTRO_NAME` environment variable.","code":"pub fn wsl_prefix(\n &mut self,\n wsl_prefix: Option,\n ) -> &mut HyperlinkEnvironment {\n self.wsl_prefix = wsl_prefix;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":286,"symbol":"HyperlinkFormatError","kind":"type","lang":"rust","doc":"An error that can occur when parsing a hyperlink format.","code":"pub struct HyperlinkFormatError {\n kind: HyperlinkFormatErrorKind,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":291,"symbol":"HyperlinkFormatErrorKind","kind":"type","lang":"rust","code":"enum HyperlinkFormatErrorKind {\n /// This occurs when there are zero variables in the format.\n NoVariables,\n /// This occurs when the {path} variable is missing.\n NoPathVariable,\n /// This occurs when the {line} variable is missing, while the {column}\n /// variable is present.\n NoLineVariable,\n /// This occurs when an unknown variable is used.\n InvalidVariable(String),\n /// The format doesn't start with a valid scheme.\n InvalidScheme,\n /// This occurs when an unescaped `}` is found without a corresponding\n /// `{` preceding it.\n InvalidCloseVariable,\n /// This occurs when a `{` is found without a corresponding `}` following\n /// it.\n UnclosedVariable,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":314,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n use self::HyperlinkFormatErrorKind::*;\n\n match self.kind {\n NoVariables => {\n let mut aliases = hyperlink_aliases();\n aliases.sort_by_key(|alias| {\n alias.display_priority().unwrap_or(i16::MAX)\n });\n let names: Vec<&str> =\n aliases.iter().map(|alias| alias.name()).collect();\n write!(\n f,\n \"at least a {{path}} variable is required in a \\\n hyperlink format, or otherwise use a valid alias: \\\n {aliases}\",\n aliases = names.join(\", \"),\n )\n }\n NoPathVariable => {\n write!(\n f,\n \"the {{path}} variable is required in a hyperlink format\",\n )\n }\n NoLineVariable => {\n write!(\n f,\n \"the hyperlink format contains a {{column}} variable, \\\n but no {{line}} variable is present\",\n )\n "} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":382,"symbol":"FormatBuilder","kind":"type","lang":"rust","doc":"A builder for `HyperlinkFormat`. Once a `HyperlinkFormat` is built, it is immutable.","code":"struct FormatBuilder {\n parts: Vec,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":388,"symbol":"new","kind":"function","lang":"rust","doc":"Creates a new hyperlink format builder.","code":"fn new() -> FormatBuilder {\n FormatBuilder { parts: vec![] }\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":393,"symbol":"append_slice","kind":"function","lang":"rust","doc":"Appends static text.","code":"fn append_slice(&mut self, text: &[u8]) -> &mut FormatBuilder {\n if let Some(Part::Text(contents)) = self.parts.last_mut() {\n contents.extend_from_slice(text);\n } else if !text.is_empty() {\n self.parts.push(Part::Text(text.to_vec()));\n }\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":403,"symbol":"append_char","kind":"function","lang":"rust","doc":"Appends a single character.","code":"fn append_char(&mut self, ch: char) -> &mut FormatBuilder {\n self.append_slice(ch.encode_utf8(&mut [0; 4]).as_bytes())\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":409,"symbol":"append_var","kind":"function","lang":"rust","doc":"Appends a variable with the given name. If the name isn't recognized, then this returns an error.","code":"fn append_var(\n &mut self,\n name: &str,\n ) -> Result<&mut FormatBuilder, HyperlinkFormatError> {\n let part = match name {\n \"host\" => Part::Host,\n \"wslprefix\" => Part::WSLPrefix,\n \"path\" => Part::Path,\n \"line\" => Part::Line,\n \"column\" => Part::Column,\n unknown => {\n let err = HyperlinkFormatError {\n kind: HyperlinkFormatErrorKind::InvalidVariable(\n unknown.to_string(),\n ),\n };\n return Err(err);\n }\n };\n self.parts.push(part);\n Ok(self)\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":433,"symbol":"build","kind":"function","lang":"rust","doc":"Builds the format.","code":"fn build(&self) -> Result {\n self.validate()?;\n Ok(HyperlinkFormat {\n parts: self.parts.clone(),\n is_line_dependent: self.parts.contains(&Part::Line),\n })\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":442,"symbol":"validate","kind":"function","lang":"rust","doc":"Validate that the format is well-formed.","code":"fn validate(&self) -> Result<(), HyperlinkFormatError> {\n use self::HyperlinkFormatErrorKind::*;\n\n let err = |kind| HyperlinkFormatError { kind };\n // An empty format is fine. It just means hyperlink support is\n // disabled.\n if self.parts.is_empty() {\n return Ok(());\n }\n // If all parts are just text, then there are no variables. It's\n // likely a reference to an invalid alias.\n if self.parts.iter().all(|p| matches!(*p, Part::Text(_))) {\n return Err(err(NoVariables));\n }\n // Even if we have other variables, no path variable means the\n // hyperlink can't possibly work the way it is intended.\n if !self.parts.contains(&Part::Path) {\n return Err(err(NoPathVariable));\n }\n // If the {column} variable is used, then we also need a {line}\n // variable or else {column} can't possibly work.\n if self.parts.contains(&Part::Column)\n && !self.parts.contains(&Part::Line)\n {\n return Err(err(NoLineVariable));\n }\n self.validate_scheme()\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":481,"symbol":"validate_scheme","kind":"function","lang":"rust","doc":"scheme = 1*[ lowalpha | digit | \"+\" | \"-\" | \".\" ] but is case insensitive. [1]: https://datatracker.ietf.org/doc/html/rfc1738#section-2.1 [2]: https://datatracker.ietf.org/doc/html/rfc1738#section-5","code":"fn validate_scheme(&self) -> Result<(), HyperlinkFormatError> {\n let err_invalid_scheme = HyperlinkFormatError {\n kind: HyperlinkFormatErrorKind::InvalidScheme,\n };\n let Some(Part::Text(part)) = self.parts.first() else {\n return Err(err_invalid_scheme);\n };\n let Some(colon) = part.find_byte(b':') else {\n return Err(err_invalid_scheme);\n };\n let scheme = &part[..colon];\n if scheme.is_empty() {\n return Err(err_invalid_scheme);\n }\n let is_valid_scheme_char = |byte| match byte {\n b'0'..=b'9' | b'A'..=b'Z' | b'a'..=b'z' | b'+' | b'-' | b'.' => {\n true\n }\n _ => false,\n };\n if !scheme.iter().all(|&b| is_valid_scheme_char(b)) {\n return Err(err_invalid_scheme);\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":513,"symbol":"Part","kind":"type","lang":"rust","doc":"A hyperlink format part. A sequence of these corresponds to a complete format. (Not all sequences are valid.)","code":"enum Part {\n /// Static text.\n ///\n /// We use `Vec` here (and more generally treat a format string as a\n /// sequence of bytes) because file paths may be arbitrary bytes. A rare\n /// case, but one for which there is no good reason to choke on.\n Text(Vec),\n /// Variable for the hostname.\n Host,\n /// Variable for a WSL path prefix.\n WSLPrefix,\n /// Variable for the file path.\n Path,\n /// Variable for the line number.\n Line,\n /// Variable for the column number.\n Column,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":535,"symbol":"interpolate_to","kind":"function","lang":"rust","doc":"Interpolate this part using the given `env` and `values`, and write the result of interpolation to the buffer provided.","code":"fn interpolate_to(\n &self,\n env: &HyperlinkEnvironment,\n values: &Values,\n dest: &mut Vec,\n ) {\n match *self {\n Part::Text(ref text) => dest.extend_from_slice(text),\n Part::Host => dest.extend_from_slice(\n env.host.as_ref().map(|s| s.as_bytes()).unwrap_or(b\"\"),\n ),\n Part::WSLPrefix => dest.extend_from_slice(\n env.wsl_prefix.as_ref().map(|s| s.as_bytes()).unwrap_or(b\"\"),\n ),\n Part::Path => dest.extend_from_slice(&values.path.0),\n Part::Line => {\n let line = DecimalFormatter::new(values.line.unwrap_or(1));\n dest.extend_from_slice(line.as_bytes());\n }\n Part::Column => {\n let column = DecimalFormatter::new(values.column.unwrap_or(1));\n dest.extend_from_slice(column.as_bytes());\n }\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":563,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n match self {\n Part::Text(text) => write!(f, \"{}\", String::from_utf8_lossy(text)),\n Part::Host => write!(f, \"{{host}}\"),\n Part::WSLPrefix => write!(f, \"{{wslprefix}}\"),\n Part::Path => write!(f, \"{{path}}\"),\n Part::Line => write!(f, \"{{line}}\"),\n Part::Column => write!(f, \"{{column}}\"),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":581,"symbol":"Values","kind":"type","lang":"rust","doc":"The values to replace the format variables with. This only consists of values that depend on each path or match printed. Values that are invariant throughout the lifetime of the process are set via a [`HyperlinkEnvironment`].","code":"pub(crate) struct Values<'a> {\n path: &'a HyperlinkPath,\n line: Option,\n column: Option,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":592,"symbol":"new","kind":"function","lang":"rust","doc":"Creates a new set of values, starting with the path given. Callers may also set the line and column number using the mutator methods.","code":"pub(crate) fn new(path: &'a HyperlinkPath) -> Values<'a> {\n Values { path, line: None, column: None }\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":600,"symbol":"line","kind":"function","lang":"rust","doc":"Sets the line number for these values. If a line number is not set and a hyperlink format contains a `{line}` variable, then it is interpolated with the value of `1` automatically.","code":"pub(crate) fn line(mut self, line: Option) -> Values<'a> {\n self.line = line;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":610,"symbol":"column","kind":"function","lang":"rust","doc":"Sets the column number for these values. If a column number is not set and a hyperlink format contains a `{column}` variable, then it is interpolated with the value of `1` automatically.","code":"pub(crate) fn column(mut self, column: Option) -> Values<'a> {\n self.column = column;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":626,"symbol":"Interpolator","kind":"type","lang":"rust","doc":"Interpolation of variables occurs through two different sources. The first is via a `HyperlinkEnvironment` for values that are expected to be invariant. This comes from the `HyperlinkConfig` used to build this interpolator. The second source is via `Values`, which is provided to `Interpolator::begin`. The `Values` contains things like the file path, line number and column number.","code":"pub(crate) struct Interpolator {\n config: HyperlinkConfig,\n buf: RefCell>,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":633,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new interpolator for the given hyperlink format configuration.","code":"pub(crate) fn new(config: &HyperlinkConfig) -> Interpolator {\n Interpolator { config: config.clone(), buf: RefCell::new(vec![]) }\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":646,"symbol":"begin","kind":"function","lang":"rust","doc":"This returns an interpolator status which indicates whether the hyperlink was written. It might not be written, for example, if the underlying writer doesn't support hyperlinks or if the hyperlink format is empty. The status should be provided to `Interpolator::end` as an instruction for whether to close the hyperlink or not.","code":"pub(crate) fn begin(\n &self,\n values: &Values,\n mut wtr: W,\n ) -> io::Result {\n if self.config.format().is_empty()\n || !wtr.supports_hyperlinks()\n || !wtr.supports_color()\n {\n return Ok(InterpolatorStatus::inactive());\n }\n let mut buf = self.buf.borrow_mut();\n buf.clear();\n for part in self.config.format().parts.iter() {\n part.interpolate_to(self.config.environment(), values, &mut buf);\n }\n let spec = HyperlinkSpec::open(&buf);\n wtr.set_hyperlink(&spec)?;\n Ok(InterpolatorStatus { active: true })\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":675,"symbol":"finish","kind":"function","lang":"rust","doc":"The status given should be returned from a corresponding `Interpolator::begin` call. Since `begin` may not write a hyperlink (e.g., if the underlying writer doesn't support hyperlinks), it follows that `finish` must not close a hyperlink that was never opened. The status indicates whether the hyperlink was opened or not.","code":"pub(crate) fn finish(\n &self,\n status: InterpolatorStatus,\n mut wtr: W,\n ) -> io::Result<()> {\n if !status.active {\n return Ok(());\n }\n wtr.set_hyperlink(&HyperlinkSpec::close())\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":693,"symbol":"InterpolatorStatus","kind":"type","lang":"rust","doc":"A status indicating whether a hyperlink was written or not. This is created by `Interpolator::begin` and used by `Interpolator::finish` to determine whether a hyperlink was actually opened or not. If it wasn't opened, then finishing interpolation is a no-op.","code":"pub(crate) struct InterpolatorStatus {\n active: bool,\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":700,"symbol":"inactive","kind":"function","lang":"rust","doc":"Create an inactive interpolator status.","code":"pub(crate) fn inactive() -> InterpolatorStatus {\n InterpolatorStatus { active: false }\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":710,"symbol":"HyperlinkPath","kind":"type","lang":"rust","doc":"Represents the `{path}` part of a hyperlink. This is the value to use as-is in the hyperlink, converted from an OS file path.","code":"pub(crate) struct HyperlinkPath(Vec);"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":715,"symbol":"from_path","kind":"function","lang":"rust","doc":"Returns a hyperlink path from an OS path.","code":"pub(crate) fn from_path(original_path: &Path) -> Option {\n use std::os::unix::ffi::OsStrExt;\n\n // We canonicalize the path in order to get an absolute version of it\n // without any `.` or `..` or superfluous separators. Unfortunately,\n // this does also remove symlinks, and in theory, it would be nice to\n // retain them. Perhaps even simpler, we could just join the current\n // working directory with the path and be done with it. There was\n // some discussion about this on PR#2483, and there generally appears\n // to be some uncertainty about the extent to which hyperlinks with\n // things like `..` in them actually work. So for now, we do the safest\n // thing possible even though I think it can result in worse user\n // experience. (Because it means the path you click on and the actual\n // path that gets followed are different, even though they ostensibly\n // refer to the same file.)\n //\n // There's also the potential issue that path canonicalization is\n // expensive since it can touch the file system. That is probably\n // less of an issue since hyperli"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":768,"symbol":"from_path","kind":"function","lang":"rust","doc":"Returns a hyperlink path from an OS path.","code":"pub(crate) fn from_path(original_path: &Path) -> Option {\n // On Windows, we use `std::path::absolute` instead of `Path::canonicalize`\n // as it can be much faster since it does not touch the file system.\n // It wraps the [`GetFullPathNameW`][1] API, except for verbatim paths\n // (those which start with `\\\\?\\`, see [the documentation][2] for details).\n //\n // Here, we strip any verbatim path prefixes since we cannot use them\n // in hyperlinks anyway. This can only happen if the user explicitly\n // supplies a verbatim path as input, which already needs to be absolute:\n //\n // \\\\?\\C:\\dir\\file.txt (local path)\n // \\\\?\\UNC\\server\\dir\\file.txt (network share)\n //\n // The `\\\\?\\` prefix is constant for verbatim paths, and can be followed\n // by `UNC\\` (universal naming convention), which denotes a network share.\n //\n // Given that the default URL format on Windows is file://{path}\n // we need to return the following from this function:\n //\n // /C:/dir/file.txt (local path)\n // //server/dir/file.txt (network "} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":881,"symbol":"from_path","kind":"function","lang":"rust","doc":"For other platforms (not windows, not unix), return None and log a debug message.","code":"pub(crate) fn from_path(original_path: &Path) -> Option {\n log::debug!(\"hyperlinks are not supported on this platform\");\n None\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":898,"symbol":"encode","kind":"function","lang":"rust","doc":"Section 4 of RFC 8089 (The \"file\" URI Scheme) does not mandate precise encoding requirements for non-ASCII characters, and this implementation leaves them unencoded. On Windows, the UrlCreateFromPathW function does not encode non-ASCII characters. Doing so with UTF-8 encoded paths creates invalid file:// URLs on that platform.","code":"fn encode(input: &[u8]) -> HyperlinkPath {\n let mut result = Vec::with_capacity(input.len());\n for &byte in input.iter() {\n match byte {\n b'0'..=b'9'\n | b'A'..=b'Z'\n | b'a'..=b'z'\n | b'/'\n | b':'\n | b'-'\n | b'.'\n | b'_'\n | b'~'\n | 128.. => {\n result.push(byte);\n }\n #[cfg(windows)]\n b'\\\\' => {\n result.push(b'/');\n }\n _ => {\n const HEX: &[u8] = b\"0123456789ABCDEF\";\n result.push(b'%');\n result.push(HEX[(byte >> 4) as usize]);\n result.push(HEX[(byte & 0xF) as usize]);\n }\n }\n }\n HyperlinkPath(result)\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":946,"symbol":"hyperlink_aliases","kind":"function","lang":"rust","doc":"The list returned is guaranteed to be sorted lexicographically by the alias name. Callers may want to re-sort the list using [`HyperlinkAlias::display_priority`] via a stable sort when showing the list to users. This will cause special aliases like `none` and `default` to appear first.","code":"pub fn hyperlink_aliases() -> Vec {\n HYPERLINK_PATTERN_ALIASES.iter().cloned().collect()\n}"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":957,"symbol":"build_format","kind":"function","lang":"rust","code":"fn build_format() {\n let format = FormatBuilder::new()\n .append_slice(b\"foo://\")\n .append_slice(b\"bar-\")\n .append_slice(b\"baz\")\n .append_var(\"path\")\n .unwrap()\n .build()\n .unwrap();\n\n assert_eq!(format.to_string(), \"foo://bar-baz{path}\");\n assert_eq!(format.parts[0], Part::Text(b\"foo://bar-baz\".to_vec()));\n assert!(!format.is_empty());\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":973,"symbol":"build_empty_format","kind":"function","lang":"rust","code":"fn build_empty_format() {\n let format = FormatBuilder::new().build().unwrap();\n\n assert!(format.is_empty());\n assert_eq!(format, HyperlinkFormat::empty());\n assert_eq!(format, HyperlinkFormat::default());\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":982,"symbol":"handle_alias","kind":"function","lang":"rust","code":"fn handle_alias() {\n assert!(HyperlinkFormat::from_str(\"file\").is_ok());\n assert!(HyperlinkFormat::from_str(\"none\").is_ok());\n assert!(HyperlinkFormat::from_str(\"none\").unwrap().is_empty());\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":989,"symbol":"parse_format","kind":"function","lang":"rust","code":"fn parse_format() {\n let format = HyperlinkFormat::from_str(\n \"foo://{host}/bar/{path}:{line}:{column}\",\n )\n .unwrap();\n\n assert_eq!(\n format.to_string(),\n \"foo://{host}/bar/{path}:{line}:{column}\"\n );\n assert_eq!(format.parts.len(), 8);\n assert!(format.parts.contains(&Part::Path));\n assert!(format.parts.contains(&Part::Line));\n assert!(format.parts.contains(&Part::Column));\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":1006,"symbol":"parse_valid","kind":"function","lang":"rust","code":"fn parse_valid() {\n assert!(HyperlinkFormat::from_str(\"\").unwrap().is_empty());\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://{path}\").unwrap().to_string(),\n \"foo://{path}\"\n );\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://{path}/bar\").unwrap().to_string(),\n \"foo://{path}/bar\"\n );\n\n HyperlinkFormat::from_str(\"f://{path}\").unwrap();\n HyperlinkFormat::from_str(\"f:{path}\").unwrap();\n HyperlinkFormat::from_str(\"f-+.:{path}\").unwrap();\n HyperlinkFormat::from_str(\"f42:{path}\").unwrap();\n HyperlinkFormat::from_str(\"42:{path}\").unwrap();\n HyperlinkFormat::from_str(\"+:{path}\").unwrap();\n HyperlinkFormat::from_str(\"F42:{path}\").unwrap();\n HyperlinkFormat::from_str(\"F42://foo{{bar}}{path}\").unwrap();\n }"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":1028,"symbol":"parse_invalid","kind":"function","lang":"rust","code":"fn parse_invalid() {\n use super::HyperlinkFormatErrorKind::*;\n\n let err = |kind| HyperlinkFormatError { kind };\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://bar\").unwrap_err(),\n err(NoVariables),\n );\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://{line}\").unwrap_err(),\n err(NoPathVariable),\n );\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://{path\").unwrap_err(),\n err(UnclosedVariable),\n );\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://{path}:{column}\").unwrap_err(),\n err(NoLineVariable),\n );\n assert_eq!(\n HyperlinkFormat::from_str(\"{path}\").unwrap_err(),\n err(InvalidScheme),\n );\n assert_eq!(\n HyperlinkFormat::from_str(\":{path}\").unwrap_err(),\n err(InvalidScheme),\n );\n assert_eq!(\n HyperlinkFormat::from_str(\"f*:{path}\").unwrap_err(),\n err(InvalidScheme),\n );\n\n assert_eq!(\n HyperlinkFormat::from_str(\"foo://{bar}\").unwrap_err(),\n err(InvalidVariable(\"bar\".to_string())),\n );\n ass"} {"repo":"ripgrep","file":"crates/printer/src/hyperlink/mod.rs","line":1097,"symbol":"convert_to_hyperlink_path","kind":"function","lang":"rust","code":"fn convert_to_hyperlink_path() {\n let convert = |path| {\n String::from_utf8(\n HyperlinkPath::from_path(Path::new(path)).unwrap().0,\n )\n .unwrap()\n };\n\n assert_eq!(convert(r\"C:\\dir\\file.txt\"), \"/C:/dir/file.txt\");\n assert_eq!(\n convert(r\"C:\\foo\\bar\\..\\other\\baz.txt\"),\n \"/C:/foo/other/baz.txt\"\n );\n\n assert_eq!(convert(r\"\\\\server\\dir\\file.txt\"), \"//server/dir/file.txt\");\n assert_eq!(\n convert(r\"\\\\server\\dir\\foo\\..\\other\\file.txt\"),\n \"//server/dir/other/file.txt\"\n );\n\n assert_eq!(convert(r\"\\\\?\\C:\\dir\\file.txt\"), \"/C:/dir/file.txt\");\n assert_eq!(\n convert(r\"\\\\?\\UNC\\server\\dir\\file.txt\"),\n \"//server/dir/file.txt\"\n );\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":25,"symbol":"Config","kind":"type","lang":"rust","doc":"The configuration for the JSON printer. This is manipulated by the JSONBuilder and then referenced by the actual implementation. Once a printer is build, the configuration is frozen and cannot changed.","code":"struct Config {\n pretty: bool,\n always_begin_end: bool,\n replacement: Arc>>,\n}"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":32,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n pretty: false,\n always_begin_end: false,\n replacement: Arc::new(None),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":54,"symbol":"JSONBuilder","kind":"type","lang":"rust","doc":"Some configuration options, such as whether line numbers are included or whether contextual lines are shown, are drawn directly from the `grep_searcher::Searcher`'s configuration. Once a `JSON` printer is built, its configuration cannot be changed.","code":"pub struct JSONBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":60,"symbol":"new","kind":"function","lang":"rust","doc":"Return a new builder for configuring the JSON printer.","code":"pub fn new() -> JSONBuilder {\n JSONBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":65,"symbol":"build","kind":"function","lang":"rust","doc":"Create a JSON printer that writes results to the given writer.","code":"pub fn build(&self, wtr: W) -> JSON {\n JSON {\n config: self.config.clone(),\n wtr: CounterWriter::new(wtr),\n matches: vec![],\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":79,"symbol":"pretty","kind":"function","lang":"rust","doc":"Print JSON in a pretty printed format. Enabling this will no longer produce a \"JSON lines\" format, in that each JSON object printed may span multiple lines. This is disabled by default.","code":"pub fn pretty(&mut self, yes: bool) -> &mut JSONBuilder {\n self.config.pretty = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":91,"symbol":"always_begin_end","kind":"function","lang":"rust","doc":"when no match is found. When disabled, the `begin` and `end` messages are only shown if there is at least one `match` or `context` message. This is disabled by default.","code":"pub fn always_begin_end(&mut self, yes: bool) -> &mut JSONBuilder {\n self.config.always_begin_end = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":106,"symbol":"replacement","kind":"function","lang":"rust","doc":"which may either be in index form (e.g., `$2`) or can reference named capturing groups if present in the original pattern (e.g., `$foo`). For documentation on the full format, please see the `Capture` trait's `interpolate` method in the [grep-printer](https://docs.rs/grep-printer) crate.","code":"pub fn replacement(\n &mut self,\n replacement: Option>,\n ) -> &mut JSONBuilder {\n self.config.replacement = Arc::new(replacement);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":487,"symbol":"JSON","kind":"type","lang":"rust","code":"pub struct JSON {\n config: Config,\n wtr: CounterWriter,\n matches: Vec,\n}"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":496,"symbol":"new","kind":"function","lang":"rust","doc":"Return a JSON lines printer with a default configuration that writes matches to the given writer.","code":"pub fn new(wtr: W) -> JSON {\n JSONBuilder::new().build(wtr)\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":504,"symbol":"sink","kind":"function","lang":"rust","doc":"Return an implementation of `Sink` for the JSON printer. This does not associate the printer with a file path, which means this implementation will never print a file path along with the matches.","code":"pub fn sink<'s, M: Matcher>(\n &'s mut self,\n matcher: M,\n ) -> JSONSink<'static, 's, M, W> {\n JSONSink {\n matcher,\n replacer: Replacer::new(),\n json: self,\n path: None,\n start_time: Instant::now(),\n match_count: 0,\n binary_byte_offset: None,\n begin_printed: false,\n stats: Stats::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":525,"symbol":"sink_with_path","kind":"function","lang":"rust","doc":"Return an implementation of `Sink` associated with a file path. When the printer is associated with a path, then it may, depending on its configuration, print the path along with the matches found.","code":"pub fn sink_with_path<'p, 's, M, P>(\n &'s mut self,\n matcher: M,\n path: &'p P,\n ) -> JSONSink<'p, 's, M, W>\n where\n M: Matcher,\n P: ?Sized + AsRef,\n {\n JSONSink {\n matcher,\n replacer: Replacer::new(),\n json: self,\n path: Some(path.as_ref()),\n start_time: Instant::now(),\n match_count: 0,\n binary_byte_offset: None,\n begin_printed: false,\n stats: Stats::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":549,"symbol":"write_message","kind":"function","lang":"rust","doc":"Write the given message followed by a new line. The new line is determined from the configuration of the given searcher.","code":"fn write_message(\n &mut self,\n message: &jsont::Message<'_>,\n ) -> io::Result<()> {\n if self.config.pretty {\n json::to_writer_pretty(&mut self.wtr, message)?;\n } else {\n json::to_writer(&mut self.wtr, message)?;\n }\n let _ = self.wtr.write(b\"\\n\")?; // This will always be Ok(1) when successful.\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":566,"symbol":"has_written","kind":"function","lang":"rust","doc":"Returns true if and only if this printer has written at least one byte to the underlying writer during any of the previous searches.","code":"pub fn has_written(&self) -> bool {\n self.wtr.total_count() > 0\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":571,"symbol":"get_mut","kind":"function","lang":"rust","doc":"Return a mutable reference to the underlying writer.","code":"pub fn get_mut(&mut self) -> &mut W {\n self.wtr.get_mut()\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":577,"symbol":"into_inner","kind":"function","lang":"rust","doc":"Consume this printer and return back ownership of the underlying writer.","code":"pub fn into_inner(self) -> W {\n self.wtr.into_inner()\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":596,"symbol":"JSONSink","kind":"type","lang":"rust","doc":"* `'s` refers to the lifetime of the [`JSON`] printer that this type borrows. * `M` refers to the type of matcher used by `grep_searcher::Searcher` that is reporting results to this sink. * `W` refers to the underlying writer that this printer is writing its output to.","code":"pub struct JSONSink<'p, 's, M: Matcher, W> {\n matcher: M,\n replacer: Replacer,\n json: &'s mut JSON,\n path: Option<&'p Path>,\n start_time: Instant,\n match_count: u64,\n binary_byte_offset: Option,\n begin_printed: bool,\n stats: Stats,\n}"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":614,"symbol":"has_match","kind":"function","lang":"rust","doc":"Returns true if and only if this printer received a match in the previous search. This is unaffected by the result of searches before the previous search.","code":"pub fn has_match(&self) -> bool {\n self.match_count > 0\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":621,"symbol":"match_count","kind":"function","lang":"rust","doc":"Return the total number of matches reported to this sink. This corresponds to the number of times `Sink::matched` is called.","code":"pub fn match_count(&self) -> u64 {\n self.match_count\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":635,"symbol":"binary_byte_offset","kind":"function","lang":"rust","doc":"set of bytes searched. This is unaffected by the result of searches before the previous search. e.g., If the search prior to the previous search found binary data but the previous search found no binary data, then this will return `None`.","code":"pub fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":641,"symbol":"stats","kind":"function","lang":"rust","doc":"Return a reference to the stats produced by the printer for all searches executed on this sink.","code":"pub fn stats(&self) -> &Stats {\n &self.stats\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":647,"symbol":"record_matches","kind":"function","lang":"rust","doc":"Execute the matcher over the given bytes and record the match locations if the current configuration demands match granularity.","code":"fn record_matches(\n &mut self,\n searcher: &Searcher,\n bytes: &[u8],\n range: std::ops::Range,\n ) -> io::Result<()> {\n self.json.matches.clear();\n // If printing requires knowing the location of each individual match,\n // then compute and stored those right now for use later. While this\n // adds an extra copy for storing the matches, we do amortize the\n // allocation for it and this greatly simplifies the printing logic to\n // the extent that it's easy to ensure that we never do more than\n // one search to find the matches.\n let matches = &mut self.json.matches;\n find_iter_at_in_context(\n searcher,\n &self.matcher,\n bytes,\n range.clone(),\n |m| {\n let (s, e) = (m.start() - range.start, m.end() - range.start);\n matches.push(Match::new(s, e));\n true\n },\n )?;\n // Don't report empty matches appearing at the end of the bytes.\n if !matches.is_empty()\n && matches.last().unwrap().is_empty()\n && matches.last().unwrap().start() >= bytes.len()\n "} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":686,"symbol":"replace","kind":"function","lang":"rust","doc":"If the configuration specifies a replacement, then this executes the replacement, lazily allocating memory if necessary. To access the result of a replacement, use `replacer.replacement()`.","code":"fn replace(\n &mut self,\n searcher: &Searcher,\n bytes: &[u8],\n range: std::ops::Range,\n ) -> io::Result<()> {\n self.replacer.clear();\n if self.json.config.replacement.is_some() {\n let replacement =\n (*self.json.config.replacement).as_ref().map(|r| &*r).unwrap();\n self.replacer.replace_all(\n searcher,\n &self.matcher,\n bytes,\n range,\n replacement,\n )?;\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":708,"symbol":"write_begin_message","kind":"function","lang":"rust","doc":"Write the \"begin\" message.","code":"fn write_begin_message(&mut self) -> io::Result<()> {\n if self.begin_printed {\n return Ok(());\n }\n let msg = jsont::Message::Begin(jsont::Begin { path: self.path });\n self.json.write_message(&msg)?;\n self.begin_printed = true;\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":722,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n self.match_count += 1;\n self.write_begin_message()?;\n\n self.record_matches(\n searcher,\n mat.buffer(),\n mat.bytes_range_in_buffer(),\n )?;\n self.replace(searcher, mat.buffer(), mat.bytes_range_in_buffer())?;\n self.stats.add_matches(self.json.matches.len() as u64);\n self.stats.add_matched_lines(mat.lines().count() as u64);\n\n let submatches = SubMatches::new(\n mat.bytes(),\n &self.json.matches,\n self.replacer.replacement(),\n );\n let msg = jsont::Message::Match(jsont::Match {\n path: self.path,\n lines: mat.bytes(),\n line_number: mat.line_number(),\n absolute_offset: mat.absolute_byte_offset(),\n submatches: submatches.as_slice(),\n });\n self.json.write_message(&msg)?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":755,"symbol":"context","kind":"function","lang":"rust","code":"fn context(\n &mut self,\n searcher: &Searcher,\n ctx: &SinkContext<'_>,\n ) -> Result {\n self.write_begin_message()?;\n self.json.matches.clear();\n\n let submatches = if searcher.invert_match() {\n self.record_matches(searcher, ctx.bytes(), 0..ctx.bytes().len())?;\n self.replace(searcher, ctx.bytes(), 0..ctx.bytes().len())?;\n SubMatches::new(\n ctx.bytes(),\n &self.json.matches,\n self.replacer.replacement(),\n )\n } else {\n SubMatches::empty()\n };\n let msg = jsont::Message::Context(jsont::Context {\n path: self.path,\n lines: ctx.bytes(),\n line_number: ctx.line_number(),\n absolute_offset: ctx.absolute_byte_offset(),\n submatches: submatches.as_slice(),\n });\n self.json.write_message(&msg)?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":785,"symbol":"binary_data","kind":"function","lang":"rust","code":"fn binary_data(\n &mut self,\n searcher: &Searcher,\n binary_byte_offset: u64,\n ) -> Result {\n if searcher.binary_detection().quit_byte().is_some() {\n if let Some(ref path) = self.path {\n log::debug!(\n \"ignoring {path}: found binary data at \\\n offset {binary_byte_offset}\",\n path = path.display(),\n );\n }\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":802,"symbol":"begin","kind":"function","lang":"rust","code":"fn begin(&mut self, _searcher: &Searcher) -> Result {\n self.json.wtr.reset_count();\n self.start_time = Instant::now();\n self.match_count = 0;\n self.binary_byte_offset = None;\n\n if !self.json.config.always_begin_end {\n return Ok(true);\n }\n self.write_begin_message()?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":815,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(\n &mut self,\n _searcher: &Searcher,\n finish: &SinkFinish,\n ) -> Result<(), io::Error> {\n self.binary_byte_offset = finish.binary_byte_offset();\n self.stats.add_elapsed(self.start_time.elapsed());\n self.stats.add_searches(1);\n if self.match_count > 0 {\n self.stats.add_searches_with_match(1);\n }\n self.stats.add_bytes_searched(finish.byte_count());\n self.stats.add_bytes_printed(self.json.wtr.count());\n\n if !self.begin_printed {\n return Ok(());\n }\n let msg = jsont::Message::End(jsont::End {\n path: self.path,\n binary_offset: finish.binary_byte_offset(),\n stats: self.stats.clone(),\n });\n self.json.write_message(&msg)?;\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":847,"symbol":"SubMatches","kind":"type","lang":"rust","doc":"SubMatches represents a set of matches in a contiguous range of bytes. A simpler representation for this would just simply be `Vec`, but the common case is exactly one match per range of bytes, which we specialize here using a fixed size array without any allocation.","code":"enum SubMatches<'a> {\n Empty,\n Small([jsont::SubMatch<'a>; 1]),\n Big(Vec>),\n}"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":856,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new set of match ranges from a set of matches and the corresponding bytes that those matches apply to.","code":"fn new(\n bytes: &'a [u8],\n matches: &[Match],\n replacement: Option<(&'a [u8], &'a [Match])>,\n ) -> SubMatches<'a> {\n if matches.len() == 1 {\n let mat = matches[0];\n SubMatches::Small([jsont::SubMatch {\n m: &bytes[mat],\n replacement: replacement\n .map(|(rbuf, rmatches)| &rbuf[rmatches[0]]),\n start: mat.start(),\n end: mat.end(),\n }])\n } else {\n let mut match_ranges = vec![];\n for (i, &mat) in matches.iter().enumerate() {\n match_ranges.push(jsont::SubMatch {\n m: &bytes[mat],\n replacement: replacement\n .map(|(rbuf, rmatches)| &rbuf[rmatches[i]]),\n start: mat.start(),\n end: mat.end(),\n });\n }\n SubMatches::Big(match_ranges)\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":886,"symbol":"empty","kind":"function","lang":"rust","doc":"Create an empty set of match ranges.","code":"fn empty() -> SubMatches<'static> {\n SubMatches::Empty\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":891,"symbol":"as_slice","kind":"function","lang":"rust","doc":"Return this set of match ranges as a slice.","code":"fn as_slice(&self) -> &[jsont::SubMatch<'_>] {\n match *self {\n SubMatches::Empty => &[],\n SubMatches::Small(ref x) => x,\n SubMatches::Big(ref x) => x,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":917,"symbol":"printer_contents","kind":"function","lang":"rust","code":"fn printer_contents(printer: &mut JSON>) -> String {\n String::from_utf8(printer.get_mut().to_owned()).unwrap()\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":922,"symbol":"binary_detection","kind":"function","lang":"rust","code":"fn binary_detection() {\n use grep_searcher::BinaryDetection;\n\n const BINARY: &'static [u8] = b\"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nHolmeses, success in the province of detective work must always\nbe, to a very large extent, the result of luck. Sherlock Holmes\ncan extract a clew \\x00 from a wisp of straw or a flake of cigar ash;\nbut Doctor Watson has to have it taken out for him and dusted,\nand exhibited clearly, with a label attached.\\\n\";\n\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = JSONBuilder::new().build(vec![]);\n SearcherBuilder::new()\n .binary_detection(BinaryDetection::quit(b'\\x00'))\n .heap_limit(Some(80))\n .build()\n .search_reader(&matcher, BINARY, printer.sink(&matcher))\n .unwrap();\n let got = printer_contents(&mut printer);\n\n assert_eq!(got.lines().count(), 3);\n let last = got.lines().last().unwrap();\n assert!(last.contains(r#\"\"binary_offset\":212,\"#));\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":950,"symbol":"max_matches","kind":"function","lang":"rust","code":"fn max_matches() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = JSONBuilder::new().build(vec![]);\n SearcherBuilder::new()\n .max_matches(Some(1))\n .build()\n .search_reader(&matcher, SHERLOCK, printer.sink(&matcher))\n .unwrap();\n let got = printer_contents(&mut printer);\n\n assert_eq!(got.lines().count(), 3);\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":964,"symbol":"max_matches_after_context","kind":"function","lang":"rust","code":"fn max_matches_after_context() {\n let haystack = \"\\\na\nb\nc\nd\ne\nd\ne\nd\ne\nd\ne\n\";\n let matcher = RegexMatcher::new(r\"d\").unwrap();\n let mut printer = JSONBuilder::new().build(vec![]);\n SearcherBuilder::new()\n .after_context(2)\n .max_matches(Some(1))\n .build()\n .search_reader(\n &matcher,\n haystack.as_bytes(),\n printer.sink(&matcher),\n )\n .unwrap();\n let got = printer_contents(&mut printer);\n\n assert_eq!(got.lines().count(), 5);\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":996,"symbol":"no_match","kind":"function","lang":"rust","code":"fn no_match() {\n let matcher = RegexMatcher::new(r\"DOES NOT MATCH\").unwrap();\n let mut printer = JSONBuilder::new().build(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(&matcher, SHERLOCK, printer.sink(&matcher))\n .unwrap();\n let got = printer_contents(&mut printer);\n\n assert!(got.is_empty());\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":1009,"symbol":"always_begin_end_no_match","kind":"function","lang":"rust","code":"fn always_begin_end_no_match() {\n let matcher = RegexMatcher::new(r\"DOES NOT MATCH\").unwrap();\n let mut printer =\n JSONBuilder::new().always_begin_end(true).build(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(&matcher, SHERLOCK, printer.sink(&matcher))\n .unwrap();\n let got = printer_contents(&mut printer);\n\n assert_eq!(got.lines().count(), 2);\n assert!(got.contains(\"begin\") && got.contains(\"end\"));\n }"} {"repo":"ripgrep","file":"crates/printer/src/json.rs","line":1024,"symbol":"missing_crlf","kind":"function","lang":"rust","code":"fn missing_crlf() {\n let haystack = \"test\\r\\n\".as_bytes();\n\n let matcher = RegexMatcherBuilder::new().build(\"test\").unwrap();\n let mut printer = JSONBuilder::new().build(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(&matcher, haystack, printer.sink(&matcher))\n .unwrap();\n let got = printer_contents(&mut printer);\n assert_eq!(got.lines().count(), 3);\n assert!(\n got.lines().nth(1).unwrap().contains(r\"test\\r\\n\"),\n r\"missing 'test\\r\\n' in '{}'\",\n got.lines().nth(1).unwrap(),\n );\n\n let matcher =\n RegexMatcherBuilder::new().crlf(true).build(\"test\").unwrap();\n let mut printer = JSONBuilder::new().build(vec![]);\n SearcherBuilder::new()\n .line_terminator(LineTerminator::crlf())\n .build()\n .search_reader(&matcher, haystack, printer.sink(&matcher))\n .unwrap();\n let got = printer_contents(&mut printer);\n assert_eq!(got.lines().count(), 3);\n assert!(\n got.lines().nth(1).unwrap().contains(r\"test\\r\\n\"),\n r\"missing 'test\\r\\n' in '{}'\",\n "} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":11,"symbol":"Message","kind":"type","lang":"rust","code":"pub(crate) enum Message<'a> {\n Begin(Begin<'a>),\n End(End<'a>),\n Match(Match<'a>),\n Context(Context<'a>),\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":19,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"Message\", 2)?;\n match *self {\n Message::Begin(ref msg) => {\n state.serialize_field(\"type\", &\"begin\")?;\n state.serialize_field(\"data\", msg)?;\n }\n Message::End(ref msg) => {\n state.serialize_field(\"type\", &\"end\")?;\n state.serialize_field(\"data\", msg)?;\n }\n Message::Match(ref msg) => {\n state.serialize_field(\"type\", &\"match\")?;\n state.serialize_field(\"data\", msg)?;\n }\n Message::Context(ref msg) => {\n state.serialize_field(\"type\", &\"context\")?;\n state.serialize_field(\"data\", msg)?;\n }\n }\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":48,"symbol":"Begin","kind":"type","lang":"rust","code":"pub(crate) struct Begin<'a> {\n pub(crate) path: Option<&'a Path>,\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":53,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"Begin\", 1)?;\n state.serialize_field(\"path\", &self.path.map(Data::from_path))?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":65,"symbol":"End","kind":"type","lang":"rust","code":"pub(crate) struct End<'a> {\n pub(crate) path: Option<&'a Path>,\n pub(crate) binary_offset: Option,\n pub(crate) stats: crate::stats::Stats,\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":72,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"End\", 3)?;\n state.serialize_field(\"path\", &self.path.map(Data::from_path))?;\n state.serialize_field(\"binary_offset\", &self.binary_offset)?;\n state.serialize_field(\"stats\", &self.stats)?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":86,"symbol":"Match","kind":"type","lang":"rust","code":"pub(crate) struct Match<'a> {\n pub(crate) path: Option<&'a Path>,\n pub(crate) lines: &'a [u8],\n pub(crate) line_number: Option,\n pub(crate) absolute_offset: u64,\n pub(crate) submatches: &'a [SubMatch<'a>],\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":95,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"Match\", 5)?;\n state.serialize_field(\"path\", &self.path.map(Data::from_path))?;\n state.serialize_field(\"lines\", &Data::from_bytes(self.lines))?;\n state.serialize_field(\"line_number\", &self.line_number)?;\n state.serialize_field(\"absolute_offset\", &self.absolute_offset)?;\n state.serialize_field(\"submatches\", &self.submatches)?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":111,"symbol":"Context","kind":"type","lang":"rust","code":"pub(crate) struct Context<'a> {\n pub(crate) path: Option<&'a Path>,\n pub(crate) lines: &'a [u8],\n pub(crate) line_number: Option,\n pub(crate) absolute_offset: u64,\n pub(crate) submatches: &'a [SubMatch<'a>],\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":120,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"Context\", 5)?;\n state.serialize_field(\"path\", &self.path.map(Data::from_path))?;\n state.serialize_field(\"lines\", &Data::from_bytes(self.lines))?;\n state.serialize_field(\"line_number\", &self.line_number)?;\n state.serialize_field(\"absolute_offset\", &self.absolute_offset)?;\n state.serialize_field(\"submatches\", &self.submatches)?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":136,"symbol":"SubMatch","kind":"type","lang":"rust","code":"pub(crate) struct SubMatch<'a> {\n pub(crate) m: &'a [u8],\n pub(crate) replacement: Option<&'a [u8]>,\n pub(crate) start: usize,\n pub(crate) end: usize,\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":144,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"SubMatch\", 3)?;\n state.serialize_field(\"match\", &Data::from_bytes(self.m))?;\n if let Some(r) = self.replacement {\n state.serialize_field(\"replacement\", &Data::from_bytes(r))?;\n }\n state.serialize_field(\"start\", &self.start)?;\n state.serialize_field(\"end\", &self.end)?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":169,"symbol":"Data","kind":"type","lang":"rust","doc":"valid UTF-8. To handle this, `Data` is serialized as an object with one of two keys: `text` (for valid UTF-8) or `bytes` (for invalid UTF-8). The happy path is valid UTF-8, which streams right through as-is, since it is natively supported by JSON. When invalid UTF-8 is found, then it is represented as arbitrary bytes and base64 encoded.","code":"enum Data<'a> {\n Text { text: Cow<'a, str> },\n Bytes { bytes: &'a [u8] },\n}"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":175,"symbol":"from_bytes","kind":"function","lang":"rust","code":"fn from_bytes(bytes: &[u8]) -> Data<'_> {\n match std::str::from_utf8(bytes) {\n Ok(text) => Data::Text { text: Cow::Borrowed(text) },\n Err(_) => Data::Bytes { bytes },\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":183,"symbol":"from_path","kind":"function","lang":"rust","code":"fn from_path(path: &Path) -> Data<'_> {\n use std::os::unix::ffi::OsStrExt;\n\n match path.to_str() {\n Some(text) => Data::Text { text: Cow::Borrowed(text) },\n None => Data::Bytes { bytes: path.as_os_str().as_bytes() },\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":193,"symbol":"from_path","kind":"function","lang":"rust","code":"fn from_path(path: &Path) -> Data<'_> {\n // Using lossy conversion means some paths won't round trip precisely,\n // but it's not clear what we should actually do. Serde rejects\n // non-UTF-8 paths, and OsStr's are serialized as a sequence of UTF-16\n // code units on Windows. Neither seem appropriate for this use case,\n // so we do the easy thing for now.\n Data::Text { text: path.to_string_lossy() }\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":204,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"Data\", 1)?;\n match *self {\n Data::Text { ref text } => state.serialize_field(\"text\", text)?,\n Data::Bytes { bytes } => {\n // use base64::engine::{general_purpose::STANDARD, Engine};\n // let encoded = STANDARD.encode(bytes);\n state.serialize_field(\"bytes\", &base64_standard(bytes))?;\n }\n }\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":231,"symbol":"base64_standard","kind":"function","lang":"rust","doc":"We roll our own here instead of bringing in something heavier weight like the `base64` crate. In particular, we really don't care about perf much here, since this is only used for data or file paths that are not valid UTF-8. [1]: https://tools.ietf.org/html/rfc3548#section-3","code":"fn base64_standard(bytes: &[u8]) -> String {\n const ALPHABET: &[u8] =\n b\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n let mut out = String::new();\n let mut it = bytes.chunks_exact(3);\n while let Some(chunk) = it.next() {\n let group24 = (usize::from(chunk[0]) << 16)\n | (usize::from(chunk[1]) << 8)\n | usize::from(chunk[2]);\n let index1 = (group24 >> 18) & 0b111_111;\n let index2 = (group24 >> 12) & 0b111_111;\n let index3 = (group24 >> 6) & 0b111_111;\n let index4 = (group24 >> 0) & 0b111_111;\n out.push(char::from(ALPHABET[index1]));\n out.push(char::from(ALPHABET[index2]));\n out.push(char::from(ALPHABET[index3]));\n out.push(char::from(ALPHABET[index4]));\n }\n match it.remainder() {\n &[] => {}\n &[byte0] => {\n let group8 = usize::from(byte0);\n let index1 = (group8 >> 2) & 0b111_111;\n let index2 = (group8 << 4) & 0b111_111;\n out.push(char::from(ALPHABET[index1]));\n out.push(char::from(ALPHABET[index2]));\n out.push('=');\n out.push('=');\n }\n &[byte0, byte1] "} {"repo":"ripgrep","file":"crates/printer/src/jsont.rs","line":284,"symbol":"base64_basic","kind":"function","lang":"rust","doc":"Tests taken from RFC 4648[1]. [1]: https://datatracker.ietf.org/doc/html/rfc4648#section-10","code":"fn base64_basic() {\n let b64 = |s: &str| base64_standard(s.as_bytes());\n assert_eq!(b64(\"\"), \"\");\n assert_eq!(b64(\"f\"), \"Zg==\");\n assert_eq!(b64(\"fo\"), \"Zm8=\");\n assert_eq!(b64(\"foo\"), \"Zm9v\");\n assert_eq!(b64(\"foob\"), \"Zm9vYg==\");\n assert_eq!(b64(\"fooba\"), \"Zm9vYmE=\");\n assert_eq!(b64(\"foobar\"), \"Zm9vYmFy\");\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":13,"symbol":"Config","kind":"type","lang":"rust","doc":"A configuration for describing how paths should be written.","code":"struct Config {\n colors: ColorSpecs,\n hyperlink: HyperlinkConfig,\n separator: Option,\n terminator: u8,\n}"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":21,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n colors: ColorSpecs::default(),\n hyperlink: HyperlinkConfig::default(),\n separator: None,\n terminator: b'\\n',\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":33,"symbol":"PathPrinterBuilder","kind":"type","lang":"rust","doc":"A builder for a printer that emits file paths.","code":"pub struct PathPrinterBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":39,"symbol":"new","kind":"function","lang":"rust","doc":"Return a new path printer builder with a default configuration.","code":"pub fn new() -> PathPrinterBuilder {\n PathPrinterBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":45,"symbol":"build","kind":"function","lang":"rust","doc":"Create a new path printer with the current configuration that writes paths to the given writer.","code":"pub fn build(&self, wtr: W) -> PathPrinter {\n let interpolator =\n hyperlink::Interpolator::new(&self.config.hyperlink);\n PathPrinter { config: self.config.clone(), wtr, interpolator }\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":70,"symbol":"color_specs","kind":"function","lang":"rust","doc":"This completely overrides any previous color specifications. This does not add to any previously provided color specifications on this builder. The default color specifications provide no styling.","code":"pub fn color_specs(\n &mut self,\n specs: ColorSpecs,\n ) -> &mut PathPrinterBuilder {\n self.config.colors = specs;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":89,"symbol":"hyperlink","kind":"function","lang":"rust","doc":"is provided to `build`, then no hyperlinks will ever be printed regardless of the format provided here. This completely overrides any previous hyperlink format. The default configuration results in not emitting any hyperlinks.","code":"pub fn hyperlink(\n &mut self,\n config: HyperlinkConfig,\n ) -> &mut PathPrinterBuilder {\n self.config.hyperlink = config;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":108,"symbol":"separator","kind":"function","lang":"rust","doc":"A typical use for this option is to permit cygwin users on Windows to set the path separator to `/` instead of using the system default of `\\`. This is disabled by default.","code":"pub fn separator(&mut self, sep: Option) -> &mut PathPrinterBuilder {\n self.config.separator = sep;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":119,"symbol":"terminator","kind":"function","lang":"rust","doc":"Set the path terminator used. The path terminator is a byte that is printed after every file path emitted by this printer. The default path terminator is `\\n`.","code":"pub fn terminator(&mut self, terminator: u8) -> &mut PathPrinterBuilder {\n self.config.terminator = terminator;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":142,"symbol":"PathPrinter","kind":"type","lang":"rust","doc":"* It can normalize path separators. * It permits configuring the terminator. * It allows setting the color configuration in a way that is consistent with the other printers in this crate. * It allows setting the hyperlink format in a way that is consistent with the other printers in this crate.","code":"pub struct PathPrinter {\n config: Config,\n wtr: W,\n interpolator: hyperlink::Interpolator,\n}"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":150,"symbol":"write","kind":"function","lang":"rust","doc":"Write the given path to the underlying writer.","code":"pub fn write(&mut self, path: &Path) -> io::Result<()> {\n let ppath = PrinterPath::new(path.as_ref())\n .with_separator(self.config.separator);\n if !self.wtr.supports_color() {\n self.wtr.write_all(ppath.as_bytes())?;\n } else {\n let status = self.start_hyperlink(&ppath)?;\n self.wtr.set_color(self.config.colors.path())?;\n self.wtr.write_all(ppath.as_bytes())?;\n self.wtr.reset()?;\n self.interpolator.finish(status, &mut self.wtr)?;\n }\n self.wtr.write_all(&[self.config.terminator])\n }"} {"repo":"ripgrep","file":"crates/printer/src/path.rs","line":166,"symbol":"start_hyperlink","kind":"function","lang":"rust","doc":"Starts a hyperlink span when applicable.","code":"fn start_hyperlink(\n &mut self,\n path: &PrinterPath,\n ) -> io::Result {\n let Some(hyperpath) = path.as_hyperlink() else {\n return Ok(hyperlink::InterpolatorStatus::inactive());\n };\n let values = hyperlink::Values::new(hyperpath);\n self.interpolator.begin(&values, &mut self.wtr)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":36,"symbol":"Config","kind":"type","lang":"rust","doc":"The configuration for the standard printer. This is manipulated by the StandardBuilder and then referenced by the actual implementation. Once a printer is build, the configuration is frozen and cannot changed.","code":"struct Config {\n colors: ColorSpecs,\n hyperlink: HyperlinkConfig,\n stats: bool,\n heading: bool,\n path: bool,\n only_matching: bool,\n per_match: bool,\n per_match_one_line: bool,\n replacement: Arc>>,\n max_columns: Option,\n max_columns_preview: bool,\n column: bool,\n byte_offset: bool,\n trim_ascii: bool,\n separator_search: Arc>>,\n separator_context: Arc>>,\n separator_field_match: Arc>,\n separator_field_context: Arc>,\n separator_path: Option,\n path_terminator: Option,\n}"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":60,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n colors: ColorSpecs::default(),\n hyperlink: HyperlinkConfig::default(),\n stats: false,\n heading: false,\n path: true,\n only_matching: false,\n per_match: false,\n per_match_one_line: false,\n replacement: Arc::new(None),\n max_columns: None,\n max_columns_preview: false,\n column: false,\n byte_offset: false,\n trim_ascii: false,\n separator_search: Arc::new(None),\n separator_context: Arc::new(Some(b\"--\".to_vec())),\n separator_field_match: Arc::new(b\":\".to_vec()),\n separator_field_context: Arc::new(b\"-\".to_vec()),\n separator_path: None,\n path_terminator: None,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":99,"symbol":"StandardBuilder","kind":"type","lang":"rust","doc":"Some configuration options, such as the display of line numbers or contextual lines, are drawn directly from the `grep_searcher::Searcher`'s configuration. Once a `Standard` printer is built, its configuration cannot be changed.","code":"pub struct StandardBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":105,"symbol":"new","kind":"function","lang":"rust","doc":"Return a new builder for configuring the standard printer.","code":"pub fn new() -> StandardBuilder {\n StandardBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":127,"symbol":"build","kind":"function","lang":"rust","doc":"`termcolor::Ansi` or `termcolor::NoColor` wrappers, which always enable colors via ANSI escapes or always disable colors, respectively. As a convenience, callers may use `build_no_color` to automatically select the `termcolor::NoColor` wrapper to avoid needing to import from `termcolor` explicitly.","code":"pub fn build(&self, wtr: W) -> Standard {\n Standard {\n config: self.config.clone(),\n wtr: RefCell::new(CounterWriter::new(wtr)),\n matches: vec![],\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":140,"symbol":"build_no_color","kind":"function","lang":"rust","doc":"Build a printer from any implementation of `io::Write` and never emit any colors, regardless of the user color specification settings. This is a convenience routine for `StandardBuilder::build(termcolor::NoColor::new(wtr))`.","code":"pub fn build_no_color(\n &self,\n wtr: W,\n ) -> Standard> {\n self.build(NoColor::new(wtr))\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":164,"symbol":"color_specs","kind":"function","lang":"rust","doc":"is provided to `build`, then no color will ever be printed regardless of the color specifications provided here. This completely overrides any previous color specifications. This does not add to any previously provided color specifications on this builder.","code":"pub fn color_specs(&mut self, specs: ColorSpecs) -> &mut StandardBuilder {\n self.config.colors = specs;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":180,"symbol":"hyperlink","kind":"function","lang":"rust","doc":"is provided to `build`, then no hyperlinks will ever be printed regardless of the format provided here. This completely overrides any previous hyperlink format. The default configuration results in not emitting any hyperlinks.","code":"pub fn hyperlink(\n &mut self,\n config: HyperlinkConfig,\n ) -> &mut StandardBuilder {\n self.config.hyperlink = config;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":203,"symbol":"stats","kind":"function","lang":"rust","doc":"When this is enabled, this printer may need to do extra work in order to compute certain statistics, which could cause the search to take longer. For a complete description of available statistics, see [`Stats`].","code":"pub fn stats(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.stats = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":218,"symbol":"heading","kind":"function","lang":"rust","doc":"any matches. If the heading is not the first thing emitted by the printer, then a line terminator is printed before the heading. By default, this option is disabled. When disabled, the printer will not show any heading and will instead print the file path (if one is given) on the same line as each matching (or context) line.","code":"pub fn heading(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.heading = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":229,"symbol":"path","kind":"function","lang":"rust","doc":"When enabled, if a path was given to the printer, then it is shown in the output (either as a heading or as a prefix to each matching line). When disabled, then no paths are ever included in the output even when a path is provided to the printer. This is enabled by default.","code":"pub fn path(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.path = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":238,"symbol":"only_matching","kind":"function","lang":"rust","doc":"Only print the specific matches instead of the entire line containing each match. Each match is printed on its own line. When multi line search is enabled, then matches spanning multiple lines are printed such that only the matching portions of each line are shown.","code":"pub fn only_matching(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.only_matching = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":260,"symbol":"per_match","kind":"function","lang":"rust","doc":"that match. In multi-line mode, column numbers only indicate the start of a match. Subsequent lines in a multi-line match always have a column number of `1`. When a match contains multiple lines, enabling `per_match_one_line` will cause only the first line each in match to be printed.","code":"pub fn per_match(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.per_match = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":275,"symbol":"per_match_one_line","kind":"function","lang":"rust","doc":"only ever want one line per match. This is only applicable when multi-line matching is enabled, since otherwise, matches are guaranteed to span one line. This is disabled by default.","code":"pub fn per_match_one_line(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.per_match_one_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":290,"symbol":"replacement","kind":"function","lang":"rust","doc":"which may either be in index form (e.g., `$2`) or can reference named capturing groups if present in the original pattern (e.g., `$foo`). For documentation on the full format, please see the `Capture` trait's `interpolate` method in the [grep-printer](https://docs.rs/grep-printer) crate.","code":"pub fn replacement(\n &mut self,\n replacement: Option>,\n ) -> &mut StandardBuilder {\n self.config.replacement = Arc::new(replacement);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":306,"symbol":"max_columns","kind":"function","lang":"rust","doc":"If a line is found which exceeds this maximum, then it is replaced with a message indicating that the line has been omitted. The default is to not specify a limit, in which each matching or contextual line is printed regardless of how long it is.","code":"pub fn max_columns(&mut self, limit: Option) -> &mut StandardBuilder {\n self.config.max_columns = limit;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":321,"symbol":"max_columns_preview","kind":"function","lang":"rust","doc":"The preview will correspond to the first `N` *grapheme clusters* of the line, where `N` is the limit configured by `max_columns`. If no limit is set, then enabling this has no effect. This is disabled by default.","code":"pub fn max_columns_preview(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.max_columns_preview = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":335,"symbol":"column","kind":"function","lang":"rust","doc":"line for every match along with the starting offset for that match. Column numbers are computed in terms of bytes from the start of the line being printed. This is disabled by default.","code":"pub fn column(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.column = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":347,"symbol":"byte_offset","kind":"function","lang":"rust","doc":"The absolute byte offset starts from the beginning of each search and is zero based. If the `only_matching` option is set, then this will print the absolute byte offset of the beginning of each match.","code":"pub fn byte_offset(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.byte_offset = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":356,"symbol":"trim_ascii","kind":"function","lang":"rust","doc":"When enabled, all lines will have prefix ASCII whitespace trimmed before being written. This is disabled by default.","code":"pub fn trim_ascii(&mut self, yes: bool) -> &mut StandardBuilder {\n self.config.trim_ascii = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":374,"symbol":"separator_search","kind":"function","lang":"rust","doc":"To reproduce the classic grep format, this is typically set to `--` (the same as the context separator) if and only if contextual lines have been requested, but disabled otherwise. By default, this is disabled.","code":"pub fn separator_search(\n &mut self,\n sep: Option>,\n ) -> &mut StandardBuilder {\n self.config.separator_search = Arc::new(sep);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":391,"symbol":"separator_context","kind":"function","lang":"rust","doc":"The separator is always printed on its own line, even if it's empty. If no separator is set, then nothing is printed when a context break occurs. By default, this is set to `--`.","code":"pub fn separator_context(\n &mut self,\n sep: Option>,\n ) -> &mut StandardBuilder {\n self.config.separator_context = Arc::new(sep);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":407,"symbol":"separator_field_match","kind":"function","lang":"rust","doc":"For example, when the searcher has line numbers enabled, this printer will print the line number before each matching line. The bytes given here will be written after the line number but before the matching line. By default, this is set to `:`.","code":"pub fn separator_field_match(\n &mut self,\n sep: Vec,\n ) -> &mut StandardBuilder {\n self.config.separator_field_match = Arc::new(sep);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":423,"symbol":"separator_field_context","kind":"function","lang":"rust","doc":"For example, when the searcher has line numbers enabled, this printer will print the line number before each context line. The bytes given here will be written after the line number but before the context line. By default, this is set to `-`.","code":"pub fn separator_field_context(\n &mut self,\n sep: Vec,\n ) -> &mut StandardBuilder {\n self.config.separator_field_context = Arc::new(sep);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":444,"symbol":"separator_path","kind":"function","lang":"rust","doc":"different path separator from what the current environment has configured. A typical use for this option is to permit cygwin users on Windows to set the path separator to `/` instead of using the system default of `\\`.","code":"pub fn separator_path(&mut self, sep: Option) -> &mut StandardBuilder {\n self.config.separator_path = sep;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":457,"symbol":"path_terminator","kind":"function","lang":"rust","doc":"The path terminator is a byte that is printed after every file path emitted by this printer. If no path terminator is set (the default), then paths are terminated by either new lines (for when `heading` is enabled) or the match or context field separators (e.g., `:` or `-`).","code":"pub fn path_terminator(\n &mut self,\n terminator: Option,\n ) -> &mut StandardBuilder {\n self.config.path_terminator = terminator;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":480,"symbol":"Standard","kind":"type","lang":"rust","doc":"This type is generic over `W`, which represents any implementation of the `termcolor::WriteColor` trait. If colors are not desired, then the `new_no_color` constructor can be used, or, alternatively, the `termcolor::NoColor` adapter can be used to wrap any `io::Write` implementation without enabling any colors.","code":"pub struct Standard {\n config: Config,\n wtr: RefCell>,\n matches: Vec,\n}"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":494,"symbol":"new","kind":"function","lang":"rust","doc":"matches to the given writer. The writer should be an implementation of `termcolor::WriteColor` and not just a bare implementation of `io::Write`. To use a normal `io::Write` implementation (simultaneously sacrificing colors), use the `new_no_color` constructor.","code":"pub fn new(wtr: W) -> Standard {\n StandardBuilder::new().build(wtr)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":505,"symbol":"new_no_color","kind":"function","lang":"rust","doc":"Return a standard printer with a default configuration that writes matches to the given writer. The writer can be any implementation of `io::Write`. With this constructor, the printer will never emit colors.","code":"pub fn new_no_color(wtr: W) -> Standard> {\n StandardBuilder::new().build_no_color(wtr)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":515,"symbol":"sink","kind":"function","lang":"rust","doc":"Return an implementation of `Sink` for the standard printer. This does not associate the printer with a file path, which means this implementation will never print a file path along with the matches.","code":"pub fn sink<'s, M: Matcher>(\n &'s mut self,\n matcher: M,\n ) -> StandardSink<'static, 's, M, W> {\n let interpolator =\n hyperlink::Interpolator::new(&self.config.hyperlink);\n let stats = if self.config.stats { Some(Stats::new()) } else { None };\n let needs_match_granularity = self.needs_match_granularity();\n StandardSink {\n matcher,\n standard: self,\n replacer: Replacer::new(),\n interpolator,\n path: None,\n start_time: Instant::now(),\n match_count: 0,\n binary_byte_offset: None,\n stats,\n needs_match_granularity,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":541,"symbol":"sink_with_path","kind":"function","lang":"rust","doc":"Return an implementation of `Sink` associated with a file path. When the printer is associated with a path, then it may, depending on its configuration, print the path along with the matches found.","code":"pub fn sink_with_path<'p, 's, M, P>(\n &'s mut self,\n matcher: M,\n path: &'p P,\n ) -> StandardSink<'p, 's, M, W>\n where\n M: Matcher,\n P: ?Sized + AsRef,\n {\n if !self.config.path {\n return self.sink(matcher);\n }\n let interpolator =\n hyperlink::Interpolator::new(&self.config.hyperlink);\n let stats = if self.config.stats { Some(Stats::new()) } else { None };\n let ppath = PrinterPath::new(path.as_ref())\n .with_separator(self.config.separator_path);\n let needs_match_granularity = self.needs_match_granularity();\n StandardSink {\n matcher,\n standard: self,\n replacer: Replacer::new(),\n interpolator,\n path: Some(ppath),\n start_time: Instant::now(),\n match_count: 0,\n binary_byte_offset: None,\n stats,\n needs_match_granularity,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":578,"symbol":"needs_match_granularity","kind":"function","lang":"rust","doc":"Returns true if and only if the configuration of the printer requires us to find each individual match in the lines reported by the searcher. We care about this distinction because finding each individual match costs more, so we only do it when we need to.","code":"fn needs_match_granularity(&self) -> bool {\n let supports_color = self.wtr.borrow().supports_color();\n let match_colored = !self.config.colors.matched().is_none();\n\n // Coloring requires identifying each individual match.\n (supports_color && match_colored)\n // The column feature requires finding the position of the first match.\n || self.config.column\n // Requires finding each match for performing replacement.\n || self.config.replacement.is_some()\n // Emitting a line for each match requires finding each match.\n || self.config.per_match\n // Emitting only the match requires finding each match.\n || self.config.only_matching\n // Computing certain statistics requires finding each match.\n || self.config.stats\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":600,"symbol":"has_written","kind":"function","lang":"rust","doc":"Returns true if and only if this printer has written at least one byte to the underlying writer during any of the previous searches.","code":"pub fn has_written(&self) -> bool {\n self.wtr.borrow().total_count() > 0\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":605,"symbol":"get_mut","kind":"function","lang":"rust","doc":"Return a mutable reference to the underlying writer.","code":"pub fn get_mut(&mut self) -> &mut W {\n self.wtr.get_mut().get_mut()\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":611,"symbol":"into_inner","kind":"function","lang":"rust","doc":"Consume this printer and return back ownership of the underlying writer.","code":"pub fn into_inner(self) -> W {\n self.wtr.into_inner().into_inner()\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":639,"symbol":"StandardSink","kind":"type","lang":"rust","doc":"* `'s` refers to the lifetime of the [`Standard`] printer that this type borrows. * `M` refers to the type of matcher used by `grep_searcher::Searcher` that is reporting results to this sink. * `W` refers to the underlying writer that this printer is writing its output to.","code":"pub struct StandardSink<'p, 's, M: Matcher, W> {\n matcher: M,\n standard: &'s mut Standard,\n replacer: Replacer,\n interpolator: hyperlink::Interpolator,\n path: Option>,\n start_time: Instant,\n match_count: u64,\n binary_byte_offset: Option,\n stats: Option,\n needs_match_granularity: bool,\n}"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":658,"symbol":"has_match","kind":"function","lang":"rust","doc":"Returns true if and only if this printer received a match in the previous search. This is unaffected by the result of searches before the previous search on this sink.","code":"pub fn has_match(&self) -> bool {\n self.match_count > 0\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":669,"symbol":"match_count","kind":"function","lang":"rust","doc":"This corresponds to the number of times `Sink::matched` is called on the previous search. This is unaffected by the result of searches before the previous search on this sink.","code":"pub fn match_count(&self) -> u64 {\n self.match_count\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":683,"symbol":"binary_byte_offset","kind":"function","lang":"rust","doc":"set of bytes searched. This is unaffected by the result of searches before the previous search. e.g., If the search prior to the previous search found binary data but the previous search found no binary data, then this will return `None`.","code":"pub fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":692,"symbol":"stats","kind":"function","lang":"rust","doc":"Return a reference to the stats produced by the printer for all searches executed on this sink. This only returns stats if they were requested via the [`StandardBuilder`] configuration.","code":"pub fn stats(&self) -> Option<&Stats> {\n self.stats.as_ref()\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":698,"symbol":"record_matches","kind":"function","lang":"rust","doc":"Execute the matcher over the given bytes and record the match locations if the current configuration demands match granularity.","code":"fn record_matches(\n &mut self,\n searcher: &Searcher,\n bytes: &[u8],\n range: std::ops::Range,\n ) -> io::Result<()> {\n self.standard.matches.clear();\n if !self.needs_match_granularity {\n return Ok(());\n }\n // If printing requires knowing the location of each individual match,\n // then compute and stored those right now for use later. While this\n // adds an extra copy for storing the matches, we do amortize the\n // allocation for it and this greatly simplifies the printing logic to\n // the extent that it's easy to ensure that we never do more than\n // one search to find the matches (well, for replacements, we do one\n // additional search to perform the actual replacement).\n let matches = &mut self.standard.matches;\n find_iter_at_in_context(\n searcher,\n &self.matcher,\n bytes,\n range.clone(),\n |m| {\n let (s, e) = (m.start() - range.start, m.end() - range.start);\n matches.push(Match::new(s, e));\n true\n },\n )?;\n // Don't report empty m"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":741,"symbol":"replace","kind":"function","lang":"rust","doc":"If the configuration specifies a replacement, then this executes the replacement, lazily allocating memory if necessary. To access the result of a replacement, use `replacer.replacement()`.","code":"fn replace(\n &mut self,\n searcher: &Searcher,\n bytes: &[u8],\n range: std::ops::Range,\n ) -> io::Result<()> {\n self.replacer.clear();\n if self.standard.config.replacement.is_some() {\n let replacement =\n (*self.standard.config.replacement).as_ref().unwrap();\n self.replacer.replace_all(\n searcher,\n &self.matcher,\n bytes,\n range,\n replacement,\n )?;\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":766,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n self.match_count += 1;\n\n self.record_matches(\n searcher,\n mat.buffer(),\n mat.bytes_range_in_buffer(),\n )?;\n self.replace(searcher, mat.buffer(), mat.bytes_range_in_buffer())?;\n\n if let Some(ref mut stats) = self.stats {\n stats.add_matches(self.standard.matches.len() as u64);\n stats.add_matched_lines(mat.lines().count() as u64);\n }\n if searcher.binary_detection().convert_byte().is_some() {\n if self.binary_byte_offset.is_some() {\n return Ok(false);\n }\n }\n StandardImpl::from_match(searcher, self, mat).sink()?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":793,"symbol":"context","kind":"function","lang":"rust","code":"fn context(\n &mut self,\n searcher: &Searcher,\n ctx: &SinkContext<'_>,\n ) -> Result {\n self.standard.matches.clear();\n self.replacer.clear();\n\n if searcher.invert_match() {\n self.record_matches(searcher, ctx.bytes(), 0..ctx.bytes().len())?;\n self.replace(searcher, ctx.bytes(), 0..ctx.bytes().len())?;\n }\n if searcher.binary_detection().convert_byte().is_some() {\n if self.binary_byte_offset.is_some() {\n return Ok(false);\n }\n }\n\n StandardImpl::from_context(searcher, self, ctx).sink()?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":815,"symbol":"context_break","kind":"function","lang":"rust","code":"fn context_break(\n &mut self,\n searcher: &Searcher,\n ) -> Result {\n StandardImpl::new(searcher, self).write_context_separator()?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":823,"symbol":"binary_data","kind":"function","lang":"rust","code":"fn binary_data(\n &mut self,\n searcher: &Searcher,\n binary_byte_offset: u64,\n ) -> Result {\n if searcher.binary_detection().quit_byte().is_some() {\n if let Some(ref path) = self.path {\n log::debug!(\n \"ignoring {path}: found binary data at \\\n offset {binary_byte_offset}\",\n path = path.as_path().display(),\n );\n }\n }\n self.binary_byte_offset = Some(binary_byte_offset);\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":841,"symbol":"begin","kind":"function","lang":"rust","code":"fn begin(&mut self, _searcher: &Searcher) -> Result {\n self.standard.wtr.borrow_mut().reset_count();\n self.start_time = Instant::now();\n self.match_count = 0;\n self.binary_byte_offset = None;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":849,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(\n &mut self,\n searcher: &Searcher,\n finish: &SinkFinish,\n ) -> Result<(), io::Error> {\n if let Some(offset) = self.binary_byte_offset {\n StandardImpl::new(searcher, self).write_binary_message(offset)?;\n }\n if let Some(stats) = self.stats.as_mut() {\n stats.add_elapsed(self.start_time.elapsed());\n stats.add_searches(1);\n if self.match_count > 0 {\n stats.add_searches_with_match(1);\n }\n stats.add_bytes_searched(finish.byte_count());\n stats.add_bytes_printed(self.standard.wtr.borrow().count());\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":876,"symbol":"StandardImpl","kind":"type","lang":"rust","doc":"The actual implementation of the standard printer. This couples together the searcher, the sink implementation and information about the match. A StandardImpl is initialized every time a match or a contextual line is reported.","code":"struct StandardImpl<'a, M: Matcher, W> {\n searcher: &'a Searcher,\n sink: &'a StandardSink<'a, 'a, M, W>,\n sunk: Sunk<'a>,\n /// Set to true if and only if we are writing a match with color.\n in_color_match: Cell,\n}"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":886,"symbol":"new","kind":"function","lang":"rust","doc":"Bundle self with a searcher and return the core implementation of Sink.","code":"fn new(\n searcher: &'a Searcher,\n sink: &'a StandardSink<'_, '_, M, W>,\n ) -> StandardImpl<'a, M, W> {\n StandardImpl {\n searcher,\n sink,\n sunk: Sunk::empty(),\n in_color_match: Cell::new(false),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":900,"symbol":"from_match","kind":"function","lang":"rust","doc":"Bundle self with a searcher and return the core implementation of Sink for use with handling matching lines.","code":"fn from_match(\n searcher: &'a Searcher,\n sink: &'a StandardSink<'_, '_, M, W>,\n mat: &'a SinkMatch<'a>,\n ) -> StandardImpl<'a, M, W> {\n let sunk = Sunk::from_sink_match(\n mat,\n &sink.standard.matches,\n sink.replacer.replacement(),\n );\n StandardImpl { sunk, ..StandardImpl::new(searcher, sink) }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":915,"symbol":"from_context","kind":"function","lang":"rust","doc":"Bundle self with a searcher and return the core implementation of Sink for use with handling contextual lines.","code":"fn from_context(\n searcher: &'a Searcher,\n sink: &'a StandardSink<'_, '_, M, W>,\n ctx: &'a SinkContext<'a>,\n ) -> StandardImpl<'a, M, W> {\n let sunk = Sunk::from_sink_context(\n ctx,\n &sink.standard.matches,\n sink.replacer.replacement(),\n );\n StandardImpl { sunk, ..StandardImpl::new(searcher, sink) }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":928,"symbol":"sink","kind":"function","lang":"rust","code":"fn sink(&self) -> io::Result<()> {\n self.write_search_prelude()?;\n if self.sunk.matches().is_empty() {\n if self.multi_line() && !self.is_context() {\n self.sink_fast_multi_line()\n } else {\n self.sink_fast()\n }\n } else {\n if self.multi_line() && !self.is_context() {\n self.sink_slow_multi_line()\n } else {\n self.sink_slow()\n }\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":951,"symbol":"sink_fast","kind":"function","lang":"rust","doc":"Print matches (limited to one line) quickly by avoiding the detection of each individual match in the lines reported in the given `SinkMatch`. This should only be used when the configuration does not demand match granularity and the searcher is not in multi line mode.","code":"fn sink_fast(&self) -> io::Result<()> {\n debug_assert!(self.sunk.matches().is_empty());\n debug_assert!(!self.multi_line() || self.is_context());\n\n self.write_prelude(\n self.sunk.absolute_byte_offset(),\n self.sunk.line_number(),\n None,\n )?;\n self.write_line(self.sunk.bytes())\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":969,"symbol":"sink_fast_multi_line","kind":"function","lang":"rust","doc":"Print matches (possibly spanning more than one line) quickly by avoiding the detection of each individual match in the lines reported in the given `SinkMatch`. This should only be used when the configuration does not demand match granularity. This may be used when the searcher is in multi line mode.","code":"fn sink_fast_multi_line(&self) -> io::Result<()> {\n debug_assert!(self.sunk.matches().is_empty());\n // This isn't actually a required invariant for using this method,\n // but if we wind up here and multi line mode is disabled, then we\n // should still treat it as a bug since we should be using matched_fast\n // instead.\n debug_assert!(self.multi_line());\n\n let line_term = self.searcher.line_terminator().as_byte();\n let mut absolute_byte_offset = self.sunk.absolute_byte_offset();\n for (i, line) in self.sunk.lines(line_term).enumerate() {\n self.write_prelude(\n absolute_byte_offset,\n self.sunk.line_number().map(|n| n + i as u64),\n None,\n )?;\n absolute_byte_offset += line.len() as u64;\n\n self.write_line(line)?;\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":994,"symbol":"sink_slow","kind":"function","lang":"rust","doc":"Print a matching line where the configuration of the printer requires finding each individual match (e.g., for coloring).","code":"fn sink_slow(&self) -> io::Result<()> {\n debug_assert!(!self.sunk.matches().is_empty());\n debug_assert!(!self.multi_line() || self.is_context());\n\n if self.config().only_matching {\n for &m in self.sunk.matches() {\n self.write_prelude(\n self.sunk.absolute_byte_offset() + m.start() as u64,\n self.sunk.line_number(),\n Some(m.start() as u64 + 1),\n )?;\n\n let buf = &self.sunk.bytes()[m];\n self.write_colored_line(&[Match::new(0, buf.len())], buf)?;\n }\n } else if self.config().per_match {\n for &m in self.sunk.matches() {\n self.write_prelude(\n self.sunk.absolute_byte_offset() + m.start() as u64,\n self.sunk.line_number(),\n Some(m.start() as u64 + 1),\n )?;\n self.write_colored_line(&[m], self.sunk.bytes())?;\n }\n } else {\n self.write_prelude(\n self.sunk.absolute_byte_offset(),\n self.sunk.line_number(),\n Some(self.sunk.matches()[0].start() as u64 + "} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":1029,"symbol":"sink_slow_multi_line","kind":"function","lang":"rust","code":"fn sink_slow_multi_line(&self) -> io::Result<()> {\n debug_assert!(!self.sunk.matches().is_empty());\n debug_assert!(self.multi_line());\n\n if self.config().only_matching {\n return self.sink_slow_multi_line_only_matching();\n } else if self.config().per_match {\n return self.sink_slow_multi_per_match();\n }\n\n let line_term = self.searcher.line_terminator().as_byte();\n let bytes = self.sunk.bytes();\n let matches = self.sunk.matches();\n let mut midx = 0;\n let mut count = 0;\n let mut stepper = LineStep::new(line_term, 0, bytes.len());\n while let Some((start, end)) = stepper.next(bytes) {\n let mut line = Match::new(start, end);\n self.write_prelude(\n self.sunk.absolute_byte_offset() + line.start() as u64,\n self.sunk.line_number().map(|n| n + count),\n Some(matches[0].start() as u64 + 1),\n )?;\n count += 1;\n self.trim_ascii_prefix(bytes, &mut line);\n if self.exceeds_max_columns(&bytes[line]) {\n self.write_exceeded_line(bytes, line, matches, &mut midx)?;\n } "} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":1064,"symbol":"sink_slow_multi_line_only_matching","kind":"function","lang":"rust","code":"fn sink_slow_multi_line_only_matching(&self) -> io::Result<()> {\n let line_term = self.searcher.line_terminator().as_byte();\n let spec = self.config().colors.matched();\n let bytes = self.sunk.bytes();\n let matches = self.sunk.matches();\n let mut midx = 0;\n let mut count = 0;\n let mut stepper = LineStep::new(line_term, 0, bytes.len());\n while let Some((start, end)) = stepper.next(bytes) {\n let mut line = Match::new(start, end);\n self.trim_line_terminator(bytes, &mut line);\n self.trim_ascii_prefix(bytes, &mut line);\n while !line.is_empty() {\n if matches[midx].end() <= line.start() {\n if midx + 1 < matches.len() {\n midx += 1;\n continue;\n } else {\n break;\n }\n }\n let m = matches[midx];\n\n if line.start() < m.start() {\n let upto = cmp::min(line.end(), m.start());\n line = line.with_start(upto);\n } else {\n let upto = cmp::min(line.end(), m"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":1115,"symbol":"sink_slow_multi_per_match","kind":"function","lang":"rust","code":"fn sink_slow_multi_per_match(&self) -> io::Result<()> {\n let line_term = self.searcher.line_terminator().as_byte();\n let spec = self.config().colors.matched();\n let bytes = self.sunk.bytes();\n for &m in self.sunk.matches() {\n let mut count = 0;\n let mut stepper = LineStep::new(line_term, 0, bytes.len());\n while let Some((start, end)) = stepper.next(bytes) {\n let mut line = Match::new(start, end);\n if line.start() >= m.end() {\n break;\n } else if line.end() <= m.start() {\n count += 1;\n continue;\n }\n self.write_prelude(\n self.sunk.absolute_byte_offset() + line.start() as u64,\n self.sunk.line_number().map(|n| n + count),\n Some(m.start().saturating_sub(line.start()) as u64 + 1),\n )?;\n count += 1;\n self.trim_line_terminator(bytes, &mut line);\n self.trim_ascii_prefix(bytes, &mut line);\n if self.exceeds_max_columns(&bytes[line]) {\n self.write_exceeded_"} {"repo":"ripgrep","file":"crates/printer/src/standard.rs","line":1176,"symbol":"write_prelude","kind":"function","lang":"rust","doc":"Write the beginning part of a matching line. This (may) include things like the file path, line number among others, depending on the configuration and the parameters given.","code":"fn write_prelude(\n &self,\n absolute_byte_offset: u64,\n line_number: Option,\n column: Option,\n ) -> io::Result<()> {\n let mut prelude = PreludeWriter::new(self);\n prelude.start(line_number, column)?;\n prelude.write_path()?;\n prelude.write_line_number(line_number)?;\n prelude.write_column_number(column)?;\n prelude.write_byte_offset(absolute_byte_offset)?;\n prelude.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":13,"symbol":"Stats","kind":"type","lang":"rust","doc":"Summary statistics produced at the end of a search. When statistics are reported by a printer, they correspond to all searches executed with that printer.","code":"pub struct Stats {\n elapsed: NiceDuration,\n searches: u64,\n searches_with_match: u64,\n bytes_searched: u64,\n bytes_printed: u64,\n matched_lines: u64,\n matches: u64,\n}"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":27,"symbol":"new","kind":"function","lang":"rust","doc":"Return a new value for tracking aggregate statistics across searches. All statistics are set to `0`.","code":"pub fn new() -> Stats {\n Stats::default()\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":32,"symbol":"elapsed","kind":"function","lang":"rust","doc":"Return the total amount of time elapsed.","code":"pub fn elapsed(&self) -> Duration {\n self.elapsed.0\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":37,"symbol":"searches","kind":"function","lang":"rust","doc":"Return the total number of searches executed.","code":"pub fn searches(&self) -> u64 {\n self.searches\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":42,"symbol":"searches_with_match","kind":"function","lang":"rust","doc":"Return the total number of searches that found at least one match.","code":"pub fn searches_with_match(&self) -> u64 {\n self.searches_with_match\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":47,"symbol":"bytes_searched","kind":"function","lang":"rust","doc":"Return the total number of bytes searched.","code":"pub fn bytes_searched(&self) -> u64 {\n self.bytes_searched\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":52,"symbol":"bytes_printed","kind":"function","lang":"rust","doc":"Return the total number of bytes printed.","code":"pub fn bytes_printed(&self) -> u64 {\n self.bytes_printed\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":60,"symbol":"matched_lines","kind":"function","lang":"rust","doc":"Return the total number of lines that participated in a match. When matches may contain multiple lines then this includes every line that is part of every match.","code":"pub fn matched_lines(&self) -> u64 {\n self.matched_lines\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":67,"symbol":"matches","kind":"function","lang":"rust","doc":"Return the total number of matches. There may be multiple matches per line.","code":"pub fn matches(&self) -> u64 {\n self.matches\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":72,"symbol":"add_elapsed","kind":"function","lang":"rust","doc":"Add to the elapsed time.","code":"pub fn add_elapsed(&mut self, duration: Duration) {\n self.elapsed.0 += duration;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":77,"symbol":"add_searches","kind":"function","lang":"rust","doc":"Add to the number of searches executed.","code":"pub fn add_searches(&mut self, n: u64) {\n self.searches += n;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":82,"symbol":"add_searches_with_match","kind":"function","lang":"rust","doc":"Add to the number of searches that found at least one match.","code":"pub fn add_searches_with_match(&mut self, n: u64) {\n self.searches_with_match += n;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":87,"symbol":"add_bytes_searched","kind":"function","lang":"rust","doc":"Add to the total number of bytes searched.","code":"pub fn add_bytes_searched(&mut self, n: u64) {\n self.bytes_searched += n;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":92,"symbol":"add_bytes_printed","kind":"function","lang":"rust","doc":"Add to the total number of bytes printed.","code":"pub fn add_bytes_printed(&mut self, n: u64) {\n self.bytes_printed += n;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":97,"symbol":"add_matched_lines","kind":"function","lang":"rust","doc":"Add to the total number of lines that participated in a match.","code":"pub fn add_matched_lines(&mut self, n: u64) {\n self.matched_lines += n;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":102,"symbol":"add_matches","kind":"function","lang":"rust","doc":"Add to the total number of matches.","code":"pub fn add_matches(&mut self, n: u64) {\n self.matches += n;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":110,"symbol":"add","kind":"function","lang":"rust","code":"fn add(self, rhs: Stats) -> Stats {\n self + &rhs\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":118,"symbol":"add","kind":"function","lang":"rust","code":"fn add(self, rhs: &'a Stats) -> Stats {\n Stats {\n elapsed: NiceDuration(self.elapsed.0 + rhs.elapsed.0),\n searches: self.searches + rhs.searches,\n searches_with_match: self.searches_with_match\n + rhs.searches_with_match,\n bytes_searched: self.bytes_searched + rhs.bytes_searched,\n bytes_printed: self.bytes_printed + rhs.bytes_printed,\n matched_lines: self.matched_lines + rhs.matched_lines,\n matches: self.matches + rhs.matches,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":133,"symbol":"add_assign","kind":"function","lang":"rust","code":"fn add_assign(&mut self, rhs: Stats) {\n *self += &rhs;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":139,"symbol":"add_assign","kind":"function","lang":"rust","code":"fn add_assign(&mut self, rhs: &'a Stats) {\n self.elapsed.0 += rhs.elapsed.0;\n self.searches += rhs.searches;\n self.searches_with_match += rhs.searches_with_match;\n self.bytes_searched += rhs.bytes_searched;\n self.bytes_printed += rhs.bytes_printed;\n self.matched_lines += rhs.matched_lines;\n self.matches += rhs.matches;\n }"} {"repo":"ripgrep","file":"crates/printer/src/stats.rs","line":152,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n s: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = s.serialize_struct(\"Stats\", 7)?;\n state.serialize_field(\"elapsed\", &self.elapsed)?;\n state.serialize_field(\"searches\", &self.searches)?;\n state.serialize_field(\n \"searches_with_match\",\n &self.searches_with_match,\n )?;\n state.serialize_field(\"bytes_searched\", &self.bytes_searched)?;\n state.serialize_field(\"bytes_printed\", &self.bytes_printed)?;\n state.serialize_field(\"matched_lines\", &self.matched_lines)?;\n state.serialize_field(\"matches\", &self.matches)?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":29,"symbol":"Config","kind":"type","lang":"rust","doc":"The configuration for the summary printer. This is manipulated by the SummaryBuilder and then referenced by the actual implementation. Once a printer is build, the configuration is frozen and cannot changed.","code":"struct Config {\n kind: SummaryKind,\n colors: ColorSpecs,\n hyperlink: HyperlinkConfig,\n stats: bool,\n path: bool,\n exclude_zero: bool,\n separator_field: Arc>,\n separator_path: Option,\n path_terminator: Option,\n}"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":42,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n kind: SummaryKind::Count,\n colors: ColorSpecs::default(),\n hyperlink: HyperlinkConfig::default(),\n stats: false,\n path: true,\n exclude_zero: true,\n separator_field: Arc::new(b\":\".to_vec()),\n separator_path: None,\n path_terminator: None,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":59,"symbol":"SummaryKind","kind":"type","lang":"rust","doc":"The type of summary output (if any) to print.","code":"pub enum SummaryKind {\n /// Show only a count of the total number of matches (counting each line\n /// at most once) found.\n ///\n /// If the `path` setting is enabled, then the count is prefixed by the\n /// corresponding file path.\n Count,\n /// Show only a count of the total number of matches (counting possibly\n /// many matches on each line) found.\n ///\n /// If the `path` setting is enabled, then the count is prefixed by the\n /// corresponding file path.\n CountMatches,\n /// Show only the file path if and only if a match was found.\n ///\n /// This ignores the `path` setting and always shows the file path. If no\n /// file path is provided, then searching will immediately stop and return\n /// an error.\n PathWithMatch,\n /// Show only the file path if and only if a match was found.\n ///\n /// This ignores the `path` setting and always shows the file path. If no\n /// file path is provided, then searching will immediately stop and return\n /// an error.\n PathWithoutMatch,\n /// Don't show any output and the stop the search once a match is found.\n ///\n /// Note that if `stats` is enabled, then searching continues "} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":103,"symbol":"requires_path","kind":"function","lang":"rust","doc":"Returns true if and only if this output mode requires a file path. When an output mode requires a file path, then the summary printer will report an error at the start of every search that lacks a file path.","code":"fn requires_path(&self) -> bool {\n use self::SummaryKind::*;\n\n match *self {\n PathWithMatch | PathWithoutMatch => true,\n Count | CountMatches | QuietWithMatch | QuietWithoutMatch => false,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":114,"symbol":"requires_stats","kind":"function","lang":"rust","doc":"Returns true if and only if this output mode requires computing statistics, regardless of whether they have been enabled or not.","code":"fn requires_stats(&self) -> bool {\n use self::SummaryKind::*;\n\n match *self {\n CountMatches => true,\n Count | PathWithMatch | PathWithoutMatch | QuietWithMatch\n | QuietWithoutMatch => false,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":126,"symbol":"quit_early","kind":"function","lang":"rust","doc":"Returns true if and only if a printer using this output mode can quit after seeing the first match.","code":"fn quit_early(&self) -> bool {\n use self::SummaryKind::*;\n\n match *self {\n PathWithMatch | QuietWithMatch => true,\n Count | CountMatches | PathWithoutMatch | QuietWithoutMatch => {\n false\n }\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":147,"symbol":"SummaryBuilder","kind":"type","lang":"rust","doc":"The builder permits configuring how the printer behaves. The summary printer has fewer configuration options than the standard printer because it aims to produce aggregate output about a single search (typically just one line) instead of output for each match. Once a `Summary` printer is built, its configuration cannot be changed.","code":"pub struct SummaryBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":153,"symbol":"new","kind":"function","lang":"rust","doc":"Return a new builder for configuring the summary printer.","code":"pub fn new() -> SummaryBuilder {\n SummaryBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":175,"symbol":"build","kind":"function","lang":"rust","doc":"`termcolor::Ansi` or `termcolor::NoColor` wrappers, which always enable colors via ANSI escapes or always disable colors, respectively. As a convenience, callers may use `build_no_color` to automatically select the `termcolor::NoColor` wrapper to avoid needing to import from `termcolor` explicitly.","code":"pub fn build(&self, wtr: W) -> Summary {\n Summary {\n config: self.config.clone(),\n wtr: RefCell::new(CounterWriter::new(wtr)),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":187,"symbol":"build_no_color","kind":"function","lang":"rust","doc":"Build a printer from any implementation of `io::Write` and never emit any colors, regardless of the user color specification settings. This is a convenience routine for `SummaryBuilder::build(termcolor::NoColor::new(wtr))`.","code":"pub fn build_no_color(&self, wtr: W) -> Summary> {\n self.build(NoColor::new(wtr))\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":196,"symbol":"kind","kind":"function","lang":"rust","doc":"Set the output mode for this printer. The output mode controls how aggregate results of a search are printed. By default, this printer uses the `Count` mode.","code":"pub fn kind(&mut self, kind: SummaryKind) -> &mut SummaryBuilder {\n self.config.kind = kind;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":220,"symbol":"color_specs","kind":"function","lang":"rust","doc":"This completely overrides any previous color specifications. This does not add to any previously provided color specifications on this builder. The default color specifications provide no styling.","code":"pub fn color_specs(&mut self, specs: ColorSpecs) -> &mut SummaryBuilder {\n self.config.colors = specs;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":236,"symbol":"hyperlink","kind":"function","lang":"rust","doc":"is provided to `build`, then no hyperlinks will ever be printed regardless of the format provided here. This completely overrides any previous hyperlink format. The default configuration results in not emitting any hyperlinks.","code":"pub fn hyperlink(\n &mut self,\n config: HyperlinkConfig,\n ) -> &mut SummaryBuilder {\n self.config.hyperlink = config;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":264,"symbol":"stats","kind":"function","lang":"rust","doc":"will continue after the first match in order to compute statistics. For a complete description of available statistics, see [`Stats`]. Note that some output modes, such as `CountMatches`, automatically enable this option even if it has been explicitly disabled.","code":"pub fn stats(&mut self, yes: bool) -> &mut SummaryBuilder {\n self.config.stats = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":278,"symbol":"path","kind":"function","lang":"rust","doc":"a path is provided to the printer. This setting has no effect in `PathWithMatch` and `PathWithoutMatch` modes. This is enabled by default.","code":"pub fn path(&mut self, yes: bool) -> &mut SummaryBuilder {\n self.config.path = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":290,"symbol":"exclude_zero","kind":"function","lang":"rust","doc":"When enabled and the mode is either `Count` or `CountMatches`, then results are not printed if no matches were found. Otherwise, every search prints a result with a possibly `0` number of matches. This is enabled by default.","code":"pub fn exclude_zero(&mut self, yes: bool) -> &mut SummaryBuilder {\n self.config.exclude_zero = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":299,"symbol":"separator_field","kind":"function","lang":"rust","doc":"Set the separator used between fields for the `Count` and `CountMatches` modes. By default, this is set to `:`.","code":"pub fn separator_field(&mut self, sep: Vec) -> &mut SummaryBuilder {\n self.config.separator_field = Arc::new(sep);\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":315,"symbol":"separator_path","kind":"function","lang":"rust","doc":"A typical use for this option is to permit cygwin users on Windows to set the path separator to `/` instead of using the system default of `\\`. This is disabled by default.","code":"pub fn separator_path(&mut self, sep: Option) -> &mut SummaryBuilder {\n self.config.separator_path = sep;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":327,"symbol":"path_terminator","kind":"function","lang":"rust","doc":"The path terminator is a byte that is printed after every file path emitted by this printer. If no path terminator is set (the default), then paths are terminated by either new lines or the configured field separator.","code":"pub fn path_terminator(\n &mut self,\n terminator: Option,\n ) -> &mut SummaryBuilder {\n self.config.path_terminator = terminator;\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":349,"symbol":"Summary","kind":"type","lang":"rust","doc":"`Summary::new_no_color` constructors. However, there are a number of options that configure this printer's output. Those options can be configured using [`SummaryBuilder`]. This type is generic over `W`, which represents any implementation of the `termcolor::WriteColor` trait.","code":"pub struct Summary {\n config: Config,\n wtr: RefCell>,\n}"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":364,"symbol":"new","kind":"function","lang":"rust","doc":"The writer should be an implementation of `termcolor::WriteColor` and not just a bare implementation of `io::Write`. To use a normal `io::Write` implementation (simultaneously sacrificing colors), use the `new_no_color` constructor. The default configuration uses the `Count` summary mode.","code":"pub fn new(wtr: W) -> Summary {\n SummaryBuilder::new().build(wtr)\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":377,"symbol":"new_no_color","kind":"function","lang":"rust","doc":"matches to the given writer. The writer can be any implementation of `io::Write`. With this constructor, the printer will never emit colors. The default configuration uses the `Count` summary mode.","code":"pub fn new_no_color(wtr: W) -> Summary> {\n SummaryBuilder::new().build_no_color(wtr)\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":390,"symbol":"sink","kind":"function","lang":"rust","doc":"This does not associate the printer with a file path, which means this implementation will never print a file path. If the output mode of this summary printer does not make sense without a file path (such as `PathWithMatch` or `PathWithoutMatch`), then any searches executed using this sink will immediately quit with an error.","code":"pub fn sink<'s, M: Matcher>(\n &'s mut self,\n matcher: M,\n ) -> SummarySink<'static, 's, M, W> {\n let interpolator =\n hyperlink::Interpolator::new(&self.config.hyperlink);\n let stats = if self.config.stats || self.config.kind.requires_stats() {\n Some(Stats::new())\n } else {\n None\n };\n SummarySink {\n matcher,\n summary: self,\n interpolator,\n path: None,\n start_time: Instant::now(),\n match_count: 0,\n binary_byte_offset: None,\n stats,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":417,"symbol":"sink_with_path","kind":"function","lang":"rust","doc":"Return an implementation of `Sink` associated with a file path. When the printer is associated with a path, then it may, depending on its configuration, print the path.","code":"pub fn sink_with_path<'p, 's, M, P>(\n &'s mut self,\n matcher: M,\n path: &'p P,\n ) -> SummarySink<'p, 's, M, W>\n where\n M: Matcher,\n P: ?Sized + AsRef,\n {\n if !self.config.path && !self.config.kind.requires_path() {\n return self.sink(matcher);\n }\n let interpolator =\n hyperlink::Interpolator::new(&self.config.hyperlink);\n let stats = if self.config.stats || self.config.kind.requires_stats() {\n Some(Stats::new())\n } else {\n None\n };\n let ppath = PrinterPath::new(path.as_ref())\n .with_separator(self.config.separator_path);\n SummarySink {\n matcher,\n summary: self,\n interpolator,\n path: Some(ppath),\n start_time: Instant::now(),\n match_count: 0,\n binary_byte_offset: None,\n stats,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":454,"symbol":"has_written","kind":"function","lang":"rust","doc":"Returns true if and only if this printer has written at least one byte to the underlying writer during any of the previous searches.","code":"pub fn has_written(&self) -> bool {\n self.wtr.borrow().total_count() > 0\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":459,"symbol":"get_mut","kind":"function","lang":"rust","doc":"Return a mutable reference to the underlying writer.","code":"pub fn get_mut(&mut self) -> &mut W {\n self.wtr.get_mut().get_mut()\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":465,"symbol":"into_inner","kind":"function","lang":"rust","doc":"Consume this printer and return back ownership of the underlying writer.","code":"pub fn into_inner(self) -> W {\n self.wtr.into_inner().into_inner()\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":484,"symbol":"SummarySink","kind":"type","lang":"rust","doc":"* `'s` refers to the lifetime of the [`Summary`] printer that this type borrows. * `M` refers to the type of matcher used by `grep_searcher::Searcher` that is reporting results to this sink. * `W` refers to the underlying writer that this printer is writing its output to.","code":"pub struct SummarySink<'p, 's, M: Matcher, W> {\n matcher: M,\n summary: &'s mut Summary,\n interpolator: hyperlink::Interpolator,\n path: Option>,\n start_time: Instant,\n match_count: u64,\n binary_byte_offset: Option,\n stats: Option,\n}"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":501,"symbol":"has_match","kind":"function","lang":"rust","doc":"Returns true if and only if this printer received a match in the previous search. This is unaffected by the result of searches before the previous search.","code":"pub fn has_match(&self) -> bool {\n match self.summary.config.kind {\n SummaryKind::PathWithoutMatch | SummaryKind::QuietWithoutMatch => {\n self.match_count == 0\n }\n _ => self.match_count > 0,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":520,"symbol":"binary_byte_offset","kind":"function","lang":"rust","doc":"set of bytes searched. This is unaffected by the result of searches before the previous search. e.g., If the search prior to the previous search found binary data but the previous search found no binary data, then this will return `None`.","code":"pub fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":529,"symbol":"stats","kind":"function","lang":"rust","doc":"Return a reference to the stats produced by the printer for all searches executed on this sink. This only returns stats if they were requested via the [`SummaryBuilder`] configuration.","code":"pub fn stats(&self) -> Option<&Stats> {\n self.stats.as_ref()\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":540,"symbol":"multi_line","kind":"function","lang":"rust","doc":"multiple lines. Note that this doesn't just return whether the searcher is in multi line mode, but also checks if the matter can match over multiple lines. If it can't, then we don't need multi line handling, even if the searcher has multi line mode enabled.","code":"fn multi_line(&self, searcher: &Searcher) -> bool {\n searcher.multi_line_with_matcher(&self.matcher)\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":548,"symbol":"write_path_line","kind":"function","lang":"rust","doc":"If this printer has a file path associated with it, then this will write that path to the underlying writer followed by a line terminator. (If a path terminator is set, then that is used instead of the line terminator.)","code":"fn write_path_line(&mut self, searcher: &Searcher) -> io::Result<()> {\n if self.path.is_some() {\n self.write_path()?;\n if let Some(term) = self.summary.config.path_terminator {\n self.write(&[term])?;\n } else {\n self.write_line_term(searcher)?;\n }\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":564,"symbol":"write_path_field","kind":"function","lang":"rust","doc":"If this printer has a file path associated with it, then this will write that path to the underlying writer followed by the field separator. (If a path terminator is set, then that is used instead of the field separator.)","code":"fn write_path_field(&mut self) -> io::Result<()> {\n if self.path.is_some() {\n self.write_path()?;\n if let Some(term) = self.summary.config.path_terminator {\n self.write(&[term])?;\n } else {\n self.write(&self.summary.config.separator_field)?;\n }\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":579,"symbol":"write_path","kind":"function","lang":"rust","doc":"If this printer has a file path associated with it, then this will write that path to the underlying writer in the appropriate style (color and hyperlink).","code":"fn write_path(&mut self) -> io::Result<()> {\n if self.path.is_some() {\n let status = self.start_hyperlink()?;\n self.write_spec(\n self.summary.config.colors.path(),\n self.path.as_ref().unwrap().as_bytes(),\n )?;\n self.end_hyperlink(status)?;\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":592,"symbol":"start_hyperlink","kind":"function","lang":"rust","doc":"Starts a hyperlink span when applicable.","code":"fn start_hyperlink(\n &mut self,\n ) -> io::Result {\n let Some(hyperpath) =\n self.path.as_ref().and_then(|p| p.as_hyperlink())\n else {\n return Ok(hyperlink::InterpolatorStatus::inactive());\n };\n let values = hyperlink::Values::new(hyperpath);\n self.interpolator.begin(&values, &mut *self.summary.wtr.borrow_mut())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":604,"symbol":"end_hyperlink","kind":"function","lang":"rust","code":"fn end_hyperlink(\n &self,\n status: hyperlink::InterpolatorStatus,\n ) -> io::Result<()> {\n self.interpolator.finish(status, &mut *self.summary.wtr.borrow_mut())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":612,"symbol":"write_line_term","kind":"function","lang":"rust","doc":"Write the line terminator configured on the given searcher.","code":"fn write_line_term(&self, searcher: &Searcher) -> io::Result<()> {\n self.write(searcher.line_terminator().as_bytes())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":617,"symbol":"write_spec","kind":"function","lang":"rust","doc":"Write the given bytes using the give style.","code":"fn write_spec(&self, spec: &ColorSpec, buf: &[u8]) -> io::Result<()> {\n self.summary.wtr.borrow_mut().set_color(spec)?;\n self.write(buf)?;\n self.summary.wtr.borrow_mut().reset()?;\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":625,"symbol":"write","kind":"function","lang":"rust","doc":"Write all of the given bytes.","code":"fn write(&self, buf: &[u8]) -> io::Result<()> {\n self.summary.wtr.borrow_mut().write_all(buf)\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":633,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n let is_multi_line = self.multi_line(searcher);\n let sink_match_count = if self.stats.is_none() && !is_multi_line {\n 1\n } else {\n // This gives us as many bytes as the searcher can offer. This\n // isn't guaranteed to hold the necessary context to get match\n // detection correct (because of look-around), but it does in\n // practice.\n let buf = mat.buffer();\n let range = mat.bytes_range_in_buffer();\n let mut count = 0;\n find_iter_at_in_context(\n searcher,\n &self.matcher,\n buf,\n range,\n |_| {\n count += 1;\n true\n },\n )?;\n // Because of `find_iter_at_in_context` being a giant\n // kludge internally, it's possible that it won't find\n // *any* matches even though we clearly know that there is\n // at least one. So make sure we record at least one here.\n count.m"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":679,"symbol":"binary_data","kind":"function","lang":"rust","code":"fn binary_data(\n &mut self,\n searcher: &Searcher,\n binary_byte_offset: u64,\n ) -> Result {\n if searcher.binary_detection().quit_byte().is_some() {\n if let Some(ref path) = self.path {\n log::debug!(\n \"ignoring {path}: found binary data at \\\n offset {binary_byte_offset}\",\n path = path.as_path().display(),\n );\n }\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":696,"symbol":"begin","kind":"function","lang":"rust","code":"fn begin(&mut self, _searcher: &Searcher) -> Result {\n if self.path.is_none() && self.summary.config.kind.requires_path() {\n return Err(io::Error::error_message(format!(\n \"output kind {:?} requires a file path\",\n self.summary.config.kind,\n )));\n }\n self.summary.wtr.borrow_mut().reset_count();\n self.start_time = Instant::now();\n self.match_count = 0;\n self.binary_byte_offset = None;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":710,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(\n &mut self,\n searcher: &Searcher,\n finish: &SinkFinish,\n ) -> Result<(), io::Error> {\n self.binary_byte_offset = finish.binary_byte_offset();\n if let Some(ref mut stats) = self.stats {\n stats.add_elapsed(self.start_time.elapsed());\n stats.add_searches(1);\n if self.match_count > 0 {\n stats.add_searches_with_match(1);\n }\n stats.add_bytes_searched(finish.byte_count());\n stats.add_bytes_printed(self.summary.wtr.borrow().count());\n }\n // If our binary detection method says to quit after seeing binary\n // data, then we shouldn't print any results at all, even if we've\n // found a match before detecting binary data. The intent here is to\n // keep BinaryDetection::quit as a form of filter. Otherwise, we can\n // present a matching file with a smaller number of matches than\n // there might be, which can be quite misleading.\n //\n // If our binary detection method is to convert binary data, then we\n // don't quit and therefore search the entire contents of the file.\n //\n // There is "} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":808,"symbol":"printer_contents","kind":"function","lang":"rust","code":"fn printer_contents(printer: &mut Summary>>) -> String {\n String::from_utf8(printer.get_mut().get_ref().to_owned()).unwrap()\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":813,"symbol":"path_with_match_error","kind":"function","lang":"rust","code":"fn path_with_match_error() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::PathWithMatch)\n .build_no_color(vec![]);\n let res = SearcherBuilder::new().build().search_reader(\n &matcher,\n SHERLOCK,\n printer.sink(&matcher),\n );\n assert!(res.is_err());\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":827,"symbol":"path_without_match_error","kind":"function","lang":"rust","code":"fn path_without_match_error() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::PathWithoutMatch)\n .build_no_color(vec![]);\n let res = SearcherBuilder::new().build().search_reader(\n &matcher,\n SHERLOCK,\n printer.sink(&matcher),\n );\n assert!(res.is_err());\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":841,"symbol":"count_no_path","kind":"function","lang":"rust","code":"fn count_no_path() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(&matcher, SHERLOCK, printer.sink(&matcher))\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"2\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":856,"symbol":"count_no_path_even_with_path","kind":"function","lang":"rust","code":"fn count_no_path_even_with_path() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .path(false)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"2\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":876,"symbol":"count_path","kind":"function","lang":"rust","code":"fn count_path() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlock:2\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":895,"symbol":"count_path_with_zero","kind":"function","lang":"rust","code":"fn count_path_with_zero() {\n let matcher = RegexMatcher::new(r\"NO MATCH\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .exclude_zero(false)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlock:0\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":915,"symbol":"count_path_without_zero","kind":"function","lang":"rust","code":"fn count_path_without_zero() {\n let matcher = RegexMatcher::new(r\"NO MATCH\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .exclude_zero(true)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":935,"symbol":"count_path_field_separator","kind":"function","lang":"rust","code":"fn count_path_field_separator() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .separator_field(b\"ZZ\".to_vec())\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlockZZ2\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":955,"symbol":"count_path_terminator","kind":"function","lang":"rust","code":"fn count_path_terminator() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .path_terminator(Some(b'\\x00'))\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlock\\x002\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":975,"symbol":"count_path_separator","kind":"function","lang":"rust","code":"fn count_path_separator() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .separator_path(Some(b'\\\\'))\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"/home/andrew/sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"\\\\home\\\\andrew\\\\sherlock:2\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":995,"symbol":"count_max_matches","kind":"function","lang":"rust","code":"fn count_max_matches() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::Count)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .max_matches(Some(1))\n .build()\n .search_reader(&matcher, SHERLOCK, printer.sink(&matcher))\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"1\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":1011,"symbol":"count_matches","kind":"function","lang":"rust","code":"fn count_matches() {\n let matcher = RegexMatcher::new(r\"Watson|Sherlock\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::CountMatches)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlock:4\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":1030,"symbol":"path_with_match_found","kind":"function","lang":"rust","code":"fn path_with_match_found() {\n let matcher = RegexMatcher::new(r\"Watson\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::PathWithMatch)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlock\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":1049,"symbol":"path_with_match_not_found","kind":"function","lang":"rust","code":"fn path_with_match_not_found() {\n let matcher = RegexMatcher::new(r\"ZZZZZZZZ\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::PathWithMatch)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/summary.rs","line":1068,"symbol":"path_without_match_found","kind":"function","lang":"rust","code":"fn path_without_match_found() {\n let matcher = RegexMatcher::new(r\"ZZZZZZZZZ\").unwrap();\n let mut printer = SummaryBuilder::new()\n .kind(SummaryKind::PathWithoutMatch)\n .build_no_color(vec![]);\n SearcherBuilder::new()\n .build()\n .search_reader(\n &matcher,\n SHERLOCK,\n printer.sink_with_path(&matcher, \"sherlock\"),\n )\n .unwrap();\n\n let got = printer_contents(&mut printer);\n assert_eq_printed!(\"sherlock\\n\", got);\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":14,"symbol":"Replacer","kind":"type","lang":"rust","doc":"A type for handling replacements while amortizing allocation.","code":"pub(crate) struct Replacer {\n space: Option>,\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":18,"symbol":"Space","kind":"type","lang":"rust","code":"struct Space {\n /// The place to store capture locations.\n caps: M::Captures,\n /// The place to write a replacement to.\n dst: Vec,\n /// The place to store match offsets in terms of `dst`.\n matches: Vec,\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":28,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n let (dst, matches) = self.replacement().unwrap_or((&[], &[]));\n f.debug_struct(\"Replacer\")\n .field(\"dst\", &dst)\n .field(\"matches\", &matches)\n .finish()\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":42,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new replacer for use with a particular matcher. This constructor does not allocate. Instead, space for dealing with replacements is allocated lazily only when needed.","code":"pub(crate) fn new() -> Replacer {\n Replacer { space: None }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":51,"symbol":"replace_all","kind":"function","lang":"rust","doc":"Executes a replacement on the given haystack string by replacing all matches with the given replacement. To access the result of the replacement, use the `replacement` method. This can fail if the underlying matcher reports an error.","code":"pub(crate) fn replace_all<'a>(\n &'a mut self,\n searcher: &Searcher,\n matcher: &M,\n mut haystack: &[u8],\n range: std::ops::Range,\n replacement: &[u8],\n ) -> io::Result<()> {\n // See the giant comment in 'find_iter_at_in_context' below for why we\n // do this dance.\n let is_multi_line = searcher.multi_line_with_matcher(&matcher);\n // Get the line_terminator that was removed (if any) so we can add it\n // back.\n let line_terminator = if is_multi_line {\n if haystack[range.end..].len() >= MAX_LOOK_AHEAD {\n haystack = &haystack[..range.end + MAX_LOOK_AHEAD];\n }\n &[]\n } else {\n // When searching a single line, we should remove the line\n // terminator. Otherwise, it's possible for the regex (via\n // look-around) to observe the line terminator and not match\n // because of it.\n let mut m = Match::new(0, range.end);\n let line_terminator =\n trim_line_terminator(searcher, haystack, &mut m);\n haystack = &haystack[..m.end()];\n line_terminator\n "} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":115,"symbol":"replacement","kind":"function","lang":"rust","doc":"Return the result of the prior replacement and the match offsets for all replacement occurrences within the returned replacement buffer. If no replacement has occurred then `None` is returned.","code":"pub(crate) fn replacement<'a>(\n &'a self,\n ) -> Option<(&'a [u8], &'a [Match])> {\n match self.space {\n None => None,\n Some(ref space) => {\n if space.matches.is_empty() {\n None\n } else {\n Some((&space.dst, &space.matches))\n }\n }\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":134,"symbol":"clear","kind":"function","lang":"rust","doc":"Clear space used for performing a replacement. Subsequent calls to `replacement` after calling `clear` (but before executing another replacement) will always return `None`.","code":"pub(crate) fn clear(&mut self) {\n if let Some(ref mut space) = self.space {\n space.dst.clear();\n space.matches.clear();\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":146,"symbol":"allocate","kind":"function","lang":"rust","doc":"Allocate space for replacements when used with the given matcher and return a mutable reference to that space. This can fail if allocating space for capture locations from the given matcher fails.","code":"fn allocate(&mut self, matcher: &M) -> io::Result<&mut Space> {\n if self.space.is_none() {\n let caps =\n matcher.new_captures().map_err(io::Error::error_message)?;\n self.space = Some(Space { caps, dst: vec![], matches: vec![] });\n }\n Ok(self.space.as_mut().unwrap())\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":169,"symbol":"Sunk","kind":"type","lang":"rust","doc":"While this serves as a convenient mechanism to abstract over `SinkMatch` and `SinkContext`, this also provides a way to abstract over replacements. Namely, after a replacement, a `Sunk` value can be constructed using the results of the replacement instead of the bytes reported directly by the searcher.","code":"pub(crate) struct Sunk<'a> {\n bytes: &'a [u8],\n absolute_byte_offset: u64,\n line_number: Option,\n context_kind: Option<&'a SinkContextKind>,\n matches: &'a [Match],\n original_matches: &'a [Match],\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":180,"symbol":"empty","kind":"function","lang":"rust","code":"pub(crate) fn empty() -> Sunk<'static> {\n Sunk {\n bytes: &[],\n absolute_byte_offset: 0,\n line_number: None,\n context_kind: None,\n matches: &[],\n original_matches: &[],\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":192,"symbol":"from_sink_match","kind":"function","lang":"rust","code":"pub(crate) fn from_sink_match(\n sunk: &'a SinkMatch<'a>,\n original_matches: &'a [Match],\n replacement: Option<(&'a [u8], &'a [Match])>,\n ) -> Sunk<'a> {\n let (bytes, matches) =\n replacement.unwrap_or_else(|| (sunk.bytes(), original_matches));\n Sunk {\n bytes,\n absolute_byte_offset: sunk.absolute_byte_offset(),\n line_number: sunk.line_number(),\n context_kind: None,\n matches,\n original_matches,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":210,"symbol":"from_sink_context","kind":"function","lang":"rust","code":"pub(crate) fn from_sink_context(\n sunk: &'a SinkContext<'a>,\n original_matches: &'a [Match],\n replacement: Option<(&'a [u8], &'a [Match])>,\n ) -> Sunk<'a> {\n let (bytes, matches) =\n replacement.unwrap_or_else(|| (sunk.bytes(), original_matches));\n Sunk {\n bytes,\n absolute_byte_offset: sunk.absolute_byte_offset(),\n line_number: sunk.line_number(),\n context_kind: Some(sunk.kind()),\n matches,\n original_matches,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":228,"symbol":"context_kind","kind":"function","lang":"rust","code":"pub(crate) fn context_kind(&self) -> Option<&'a SinkContextKind> {\n self.context_kind\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":233,"symbol":"bytes","kind":"function","lang":"rust","code":"pub(crate) fn bytes(&self) -> &'a [u8] {\n self.bytes\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":238,"symbol":"matches","kind":"function","lang":"rust","code":"pub(crate) fn matches(&self) -> &'a [Match] {\n self.matches\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":243,"symbol":"original_matches","kind":"function","lang":"rust","code":"pub(crate) fn original_matches(&self) -> &'a [Match] {\n self.original_matches\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":248,"symbol":"lines","kind":"function","lang":"rust","code":"pub(crate) fn lines(&self, line_term: u8) -> LineIter<'a> {\n LineIter::new(line_term, self.bytes())\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":253,"symbol":"absolute_byte_offset","kind":"function","lang":"rust","code":"pub(crate) fn absolute_byte_offset(&self) -> u64 {\n self.absolute_byte_offset\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":258,"symbol":"line_number","kind":"function","lang":"rust","code":"pub(crate) fn line_number(&self) -> Option {\n self.line_number\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":283,"symbol":"PrinterPath","kind":"type","lang":"rust","doc":"Users of this type are expected to construct it from a normal `Path` found in the standard library. It can then be written to any `io::Write` implementation using the `as_bytes` method. This achieves platform portability with a small cost: on Windows, paths that are not valid UTF-16 will not roundtrip correctly.","code":"pub(crate) struct PrinterPath<'a> {\n // On Unix, we can re-materialize a `Path` from our `Cow<'a, [u8]>` with\n // zero cost, so there's no point in storing it. At time of writing,\n // OsStr::as_os_str_bytes (and its corresponding constructor) are not\n // stable yet. Those would let us achieve the same end portably. (As long\n // as we keep our UTF-8 requirement on Windows.)\n #[cfg(not(unix))]\n path: &'a Path,\n bytes: Cow<'a, [u8]>,\n hyperlink: OnceCell>,\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":297,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new path suitable for printing.","code":"pub(crate) fn new(path: &'a Path) -> PrinterPath<'a> {\n PrinterPath {\n #[cfg(not(unix))]\n path,\n // N.B. This is zero-cost on Unix and requires at least a UTF-8\n // check on Windows. This doesn't allocate on Windows unless the\n // path is invalid UTF-8 (which is exceptionally rare).\n bytes: Vec::from_path_lossy(path),\n hyperlink: OnceCell::new(),\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":313,"symbol":"with_separator","kind":"function","lang":"rust","doc":"Set the separator on this path. When set, `PrinterPath::as_bytes` will return the path provided but with its separator replaced with the one given.","code":"pub(crate) fn with_separator(\n mut self,\n sep: Option,\n ) -> PrinterPath<'a> {\n /// Replace the path separator in this path with the given separator\n /// and do it in place. On Windows, both `/` and `\\` are treated as\n /// path separators that are both replaced by `new_sep`. In all other\n /// environments, only `/` is treated as a path separator.\n fn replace_separator(bytes: &[u8], sep: u8) -> Vec {\n let mut bytes = bytes.to_vec();\n for b in bytes.iter_mut() {\n if *b == b'/' || (cfg!(windows) && *b == b'\\\\') {\n *b = sep;\n }\n }\n bytes\n }\n let Some(sep) = sep else { return self };\n self.bytes = Cow::Owned(replace_separator(self.as_bytes(), sep));\n self\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":321,"symbol":"replace_separator","kind":"function","lang":"rust","doc":"Replace the path separator in this path with the given separator and do it in place. On Windows, both `/` and `\\` are treated as path separators that are both replaced by `new_sep`. In all other environments, only `/` is treated as a path separator.","code":"fn replace_separator(bytes: &[u8], sep: u8) -> Vec {\n let mut bytes = bytes.to_vec();\n for b in bytes.iter_mut() {\n if *b == b'/' || (cfg!(windows) && *b == b'\\\\') {\n *b = sep;\n }\n }\n bytes\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":336,"symbol":"as_bytes","kind":"function","lang":"rust","doc":"Return the raw bytes for this path.","code":"pub(crate) fn as_bytes(&self) -> &[u8] {\n &self.bytes\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":346,"symbol":"as_hyperlink","kind":"function","lang":"rust","doc":"Return this path as a hyperlink. Note that a hyperlink may not be able to be created from a path. Namely, computing the hyperlink may require touching the file system (e.g., for path canonicalization) and that can fail. This failure is silent but is logged.","code":"pub(crate) fn as_hyperlink(&self) -> Option<&HyperlinkPath> {\n self.hyperlink\n .get_or_init(|| HyperlinkPath::from_path(self.as_path()))\n .as_ref()\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":353,"symbol":"as_path","kind":"function","lang":"rust","doc":"Return this path as an actual `Path` type.","code":"pub(crate) fn as_path(&self) -> &Path {\n #[cfg(unix)]\n fn imp<'p>(p: &'p PrinterPath<'_>) -> &'p Path {\n use std::{ffi::OsStr, os::unix::ffi::OsStrExt};\n Path::new(OsStr::from_bytes(p.as_bytes()))\n }\n #[cfg(not(unix))]\n fn imp<'p>(p: &'p PrinterPath<'_>) -> &'p Path {\n p.path\n }\n imp(self)\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":355,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp<'p>(p: &'p PrinterPath<'_>) -> &'p Path {\n use std::{ffi::OsStr, os::unix::ffi::OsStrExt};\n Path::new(OsStr::from_bytes(p.as_bytes()))\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":360,"symbol":"imp","kind":"function","lang":"rust","code":"fn imp<'p>(p: &'p PrinterPath<'_>) -> &'p Path {\n p.path\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":372,"symbol":"NiceDuration","kind":"type","lang":"rust","doc":"A type that provides \"nicer\" Display and Serialize impls for std::time::Duration. The serialization format should actually be compatible with the Deserialize impl for std::time::Duration, since this type only adds new fields.","code":"pub(crate) struct NiceDuration(pub time::Duration);"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":375,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n write!(f, \"{:0.6}s\", self.fractional_seconds())\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":384,"symbol":"fractional_seconds","kind":"function","lang":"rust","doc":"Returns the number of seconds in this duration in fraction form. The number to the left of the decimal point is the number of seconds, and the number to the right is the number of milliseconds.","code":"fn fractional_seconds(&self) -> f64 {\n let fractional = (self.0.subsec_nanos() as f64) / 1_000_000_000.0;\n self.0.as_secs() as f64 + fractional\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":392,"symbol":"serialize","kind":"function","lang":"rust","code":"fn serialize(\n &self,\n ser: S,\n ) -> Result {\n use serde::ser::SerializeStruct;\n\n let mut state = ser.serialize_struct(\"Duration\", 3)?;\n state.serialize_field(\"secs\", &self.0.as_secs())?;\n state.serialize_field(\"nanos\", &self.0.subsec_nanos())?;\n state.serialize_field(\"human\", &format!(\"{}\", self))?;\n state.end()\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":415,"symbol":"DecimalFormatter","kind":"type","lang":"rust","doc":"This avoids going through the formatting machinery which seems to substantially slow things down. The `itoa` crate does the same thing as this formatter, but is a bit faster. We roll our own which is a bit slower, but gets us enough of a win to be satisfied with and with pure safe code.","code":"pub(crate) struct DecimalFormatter {\n buf: [u8; Self::MAX_U64_LEN],\n start: usize,\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":425,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new decimal formatter for the given 64-bit unsigned integer.","code":"pub(crate) fn new(mut n: u64) -> DecimalFormatter {\n let mut buf = [0; Self::MAX_U64_LEN];\n let mut i = buf.len();\n loop {\n i -= 1;\n\n let digit = u8::try_from(n % 10).unwrap();\n n /= 10;\n buf[i] = b'0' + digit;\n if n == 0 {\n break;\n }\n }\n DecimalFormatter { buf, start: i }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":442,"symbol":"as_bytes","kind":"function","lang":"rust","doc":"Return the decimal formatted as an ASCII byte string.","code":"pub(crate) fn as_bytes(&self) -> &[u8] {\n &self.buf[self.start..]\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":452,"symbol":"trim_ascii_prefix","kind":"function","lang":"rust","doc":"Trim prefix ASCII spaces from the given slice and return the corresponding range. This stops trimming a prefix as soon as it sees non-whitespace or a line terminator.","code":"pub(crate) fn trim_ascii_prefix(\n line_term: LineTerminator,\n slice: &[u8],\n range: Match,\n) -> Match {\n fn is_space(b: u8) -> bool {\n match b {\n b'\\t' | b'\\n' | b'\\x0B' | b'\\x0C' | b'\\r' | b' ' => true,\n _ => false,\n }\n }\n\n let count = slice[range]\n .iter()\n .take_while(|&&b| -> bool {\n is_space(b) && !line_term.as_bytes().contains(&b)\n })\n .count();\n range.with_start(range.start() + count)\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":457,"symbol":"is_space","kind":"function","lang":"rust","code":"fn is_space(b: u8) -> bool {\n match b {\n b'\\t' | b'\\n' | b'\\x0B' | b'\\x0C' | b'\\r' | b' ' => true,\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":473,"symbol":"find_iter_at_in_context","kind":"function","lang":"rust","code":"pub(crate) fn find_iter_at_in_context(\n searcher: &Searcher,\n matcher: M,\n mut bytes: &[u8],\n range: std::ops::Range,\n mut matched: F,\n) -> io::Result<()>\nwhere\n M: Matcher,\n F: FnMut(Match) -> bool,\n{\n // This strange dance is to account for the possibility of look-ahead in\n // the regex. The problem here is that mat.bytes() doesn't include the\n // lines beyond the match boundaries in multi-line mode, which means that\n // when we try to rediscover the full set of matches here, the regex may no\n // longer match if it required some look-ahead beyond the matching lines.\n //\n // PCRE2 (and the grep-matcher interfaces) has no way of specifying an end\n // bound of the search. So we kludge it and let the regex engine search the\n // rest of the buffer... But to avoid things getting too crazy, we cap the\n // buffer.\n //\n // If it weren't for multi-line mode, then none of this would be needed.\n // Alternatively, if we refactored the grep interfaces to pass along the\n // full set of matches (if available) from the searcher, then that might\n // also help here. But that winds up paying an upfront unavoidable cost fo"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":535,"symbol":"trim_line_terminator","kind":"function","lang":"rust","doc":"Given a buf and some bounds, if there is a line terminator at the end of the given bounds in buf, then the bounds are trimmed to remove the line terminator, returning the slice of the removed line terminator (if any).","code":"pub(crate) fn trim_line_terminator<'b>(\n searcher: &Searcher,\n buf: &'b [u8],\n line: &mut Match,\n) -> &'b [u8] {\n let lineterm = searcher.line_terminator();\n if lineterm.is_suffix(&buf[*line]) {\n let mut end = line.end() - 1;\n if lineterm.is_crlf() && end > 0 && buf.get(end - 1) == Some(&b'\\r') {\n end -= 1;\n }\n let orig_end = line.end();\n *line = line.with_end(end);\n &buf[end..orig_end]\n } else {\n &[]\n }\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":557,"symbol":"replace_with_captures_in_context","kind":"function","lang":"rust","doc":"Like `Matcher::replace_with_captures_at`, but accepts an end bound. See also: `find_iter_at_in_context` for why we need this.","code":"fn replace_with_captures_in_context(\n matcher: M,\n bytes: &[u8],\n line_terminator: &[u8],\n range: std::ops::Range,\n caps: &mut M::Captures,\n dst: &mut Vec,\n mut append: F,\n) -> Result<(), M::Error>\nwhere\n M: Matcher,\n F: FnMut(&M::Captures, &mut Vec) -> bool,\n{\n let mut last_match = range.start;\n matcher.captures_iter_at(bytes, range.start, caps, |caps| {\n let m = caps.get(0).unwrap();\n if m.start() >= range.end {\n return false;\n }\n dst.extend(&bytes[last_match..m.start()]);\n last_match = m.end();\n append(caps, dst)\n })?;\n let end = if last_match > range.end {\n bytes.len()\n } else {\n std::cmp::min(bytes.len(), range.end)\n };\n dst.extend(&bytes[last_match..end]);\n // Add back any line terminator.\n dst.extend(line_terminator);\n Ok(())\n}"} {"repo":"ripgrep","file":"crates/printer/src/util.rs","line":596,"symbol":"custom_decimal_format","kind":"function","lang":"rust","code":"fn custom_decimal_format() {\n let fmt = |n: u64| {\n let bytes = DecimalFormatter::new(n).as_bytes().to_vec();\n String::from_utf8(bytes).unwrap()\n };\n let std = |n: u64| n.to_string();\n\n let ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 100, 123, u64::MAX];\n for n in ints {\n assert_eq!(std(n), fmt(n));\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":6,"symbol":"AstAnalysis","kind":"type","lang":"rust","doc":"The results of analyzing AST of a regular expression (e.g., for supporting smart case).","code":"pub(crate) struct AstAnalysis {\n /// True if and only if a literal uppercase character occurs in the regex.\n any_uppercase: bool,\n /// True if and only if the regex contains any literal at all.\n any_literal: bool,\n}"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":19,"symbol":"from_pattern","kind":"function","lang":"rust","doc":"Returns a `AstAnalysis` value by doing analysis on the AST of `pattern`. If `pattern` is not a valid regular expression, then `None` is returned.","code":"pub(crate) fn from_pattern(pattern: &str) -> Option {\n regex_syntax::ast::parse::Parser::new()\n .parse(pattern)\n .map(|ast| AstAnalysis::from_ast(&ast))\n .ok()\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":27,"symbol":"from_ast","kind":"function","lang":"rust","doc":"Perform an AST analysis given the AST.","code":"pub(crate) fn from_ast(ast: &Ast) -> AstAnalysis {\n let mut analysis = AstAnalysis::new();\n analysis.from_ast_impl(ast);\n analysis\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":39,"symbol":"any_uppercase","kind":"function","lang":"rust","doc":"Returns true if and only if a literal uppercase character occurs in the pattern. For example, a pattern like `\\pL` contains no uppercase literals, even though `L` is uppercase and the `\\pL` class contains uppercase characters.","code":"pub(crate) fn any_uppercase(&self) -> bool {\n self.any_uppercase\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":47,"symbol":"any_literal","kind":"function","lang":"rust","doc":"Returns true if and only if the regex contains any literal at all. For example, a pattern like `\\pL` reports `false`, but a pattern like `\\pLfoo` reports `true`.","code":"pub(crate) fn any_literal(&self) -> bool {\n self.any_literal\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":52,"symbol":"new","kind":"function","lang":"rust","doc":"Creates a new `AstAnalysis` value with an initial configuration.","code":"fn new() -> AstAnalysis {\n AstAnalysis { any_uppercase: false, any_literal: false }\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":56,"symbol":"from_ast_impl","kind":"function","lang":"rust","code":"fn from_ast_impl(&mut self, ast: &Ast) {\n if self.done() {\n return;\n }\n match *ast {\n Ast::Empty(_) => {}\n Ast::Flags(_)\n | Ast::Dot(_)\n | Ast::Assertion(_)\n | Ast::ClassUnicode(_)\n | Ast::ClassPerl(_) => {}\n Ast::Literal(ref x) => {\n self.from_ast_literal(x);\n }\n Ast::ClassBracketed(ref x) => {\n self.from_ast_class_set(&x.kind);\n }\n Ast::Repetition(ref x) => {\n self.from_ast_impl(&x.ast);\n }\n Ast::Group(ref x) => {\n self.from_ast_impl(&x.ast);\n }\n Ast::Alternation(ref alt) => {\n for x in &alt.asts {\n self.from_ast_impl(x);\n }\n }\n Ast::Concat(ref alt) => {\n for x in &alt.asts {\n self.from_ast_impl(x);\n }\n }\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":92,"symbol":"from_ast_class_set","kind":"function","lang":"rust","code":"fn from_ast_class_set(&mut self, ast: &ast::ClassSet) {\n if self.done() {\n return;\n }\n match *ast {\n ast::ClassSet::Item(ref item) => {\n self.from_ast_class_set_item(item);\n }\n ast::ClassSet::BinaryOp(ref x) => {\n self.from_ast_class_set(&x.lhs);\n self.from_ast_class_set(&x.rhs);\n }\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":107,"symbol":"from_ast_class_set_item","kind":"function","lang":"rust","code":"fn from_ast_class_set_item(&mut self, ast: &ast::ClassSetItem) {\n if self.done() {\n return;\n }\n match *ast {\n ast::ClassSetItem::Empty(_)\n | ast::ClassSetItem::Ascii(_)\n | ast::ClassSetItem::Unicode(_)\n | ast::ClassSetItem::Perl(_) => {}\n ast::ClassSetItem::Literal(ref x) => {\n self.from_ast_literal(x);\n }\n ast::ClassSetItem::Range(ref x) => {\n self.from_ast_literal(&x.start);\n self.from_ast_literal(&x.end);\n }\n ast::ClassSetItem::Bracketed(ref x) => {\n self.from_ast_class_set(&x.kind);\n }\n ast::ClassSetItem::Union(ref union) => {\n for x in &union.items {\n self.from_ast_class_set_item(x);\n }\n }\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":134,"symbol":"from_ast_literal","kind":"function","lang":"rust","code":"fn from_ast_literal(&mut self, ast: &ast::Literal) {\n self.any_literal = true;\n self.any_uppercase = self.any_uppercase || ast.c.is_uppercase();\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":141,"symbol":"done","kind":"function","lang":"rust","doc":"Returns true if and only if the attributes can never change no matter what other AST it might see.","code":"fn done(&self) -> bool {\n self.any_uppercase && self.any_literal\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":150,"symbol":"analysis","kind":"function","lang":"rust","code":"fn analysis(pattern: &str) -> AstAnalysis {\n AstAnalysis::from_pattern(pattern).unwrap()\n }"} {"repo":"ripgrep","file":"crates/regex/src/ast.rs","line":155,"symbol":"various","kind":"function","lang":"rust","code":"fn various() {\n let x = analysis(\"\");\n assert!(!x.any_uppercase);\n assert!(!x.any_literal);\n\n let x = analysis(\"foo\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(\"Foo\");\n assert!(x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(\"foO\");\n assert!(x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo\\\\\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo\\w\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo\\S\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo\\p{Ll}\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo[a-z]\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo[A-Z]\");\n assert!(x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo[\\S\\t]\");\n assert!(!x.any_uppercase);\n assert!(x.any_literal);\n\n let x = analysis(r\"foo\\\\S\");\n "} {"repo":"ripgrep","file":"crates/regex/src/ban.rs","line":8,"symbol":"check","kind":"function","lang":"rust","doc":"Returns an error when a sub-expression in `expr` must match `byte`.","code":"pub(crate) fn check(expr: &Hir, byte: u8) -> Result<(), Error> {\n assert!(byte.is_ascii(), \"ban byte must be ASCII\");\n let ch = char::from(byte);\n let invalid = || Err(Error::new(ErrorKind::Banned(byte)));\n match *expr.kind() {\n HirKind::Empty => {}\n HirKind::Literal(hir::Literal(ref lit)) => {\n if lit.iter().find(|&&b| b == byte).is_some() {\n return invalid();\n }\n }\n HirKind::Class(hir::Class::Unicode(ref cls)) => {\n if cls.ranges().iter().map(|r| r.len()).sum::() == 1 {\n let contains =\n |r: &&ClassUnicodeRange| r.start() <= ch && ch <= r.end();\n if cls.ranges().iter().find(contains).is_some() {\n return invalid();\n }\n }\n }\n HirKind::Class(hir::Class::Bytes(ref cls)) => {\n if cls.ranges().iter().map(|r| r.len()).sum::() == 1 {\n let contains = |r: &&ClassBytesRange| {\n r.start() <= byte && byte <= r.end()\n };\n if cls.ranges().iter().find(contains).is_some() {\n return invalid();\n "} {"repo":"ripgrep","file":"crates/regex/src/ban.rs","line":61,"symbol":"check","kind":"function","lang":"rust","doc":"Returns true when the given pattern is detected to contain the given banned byte.","code":"fn check(pattern: &str, byte: u8) -> bool {\n let hir = Parser::new().parse(pattern).unwrap();\n super::check(&hir, byte).is_err()\n }"} {"repo":"ripgrep","file":"crates/regex/src/ban.rs","line":67,"symbol":"various","kind":"function","lang":"rust","code":"fn various() {\n assert!(check(r\"\\x00\", 0));\n assert!(check(r\"a\\x00\", 0));\n assert!(check(r\"\\x00b\", 0));\n assert!(check(r\"a\\x00b\", 0));\n assert!(check(r\"\\x00|ab\", 0));\n assert!(check(r\"ab|\\x00\", 0));\n assert!(check(r\"\\x00?\", 0));\n assert!(check(r\"(\\x00)\", 0));\n\n assert!(check(r\"[\\x00]\", 0));\n assert!(check(r\"[^[^\\x00]]\", 0));\n\n assert!(!check(r\"[^\\x00]\", 0));\n assert!(!check(r\"[\\x00a]\", 0));\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":25,"symbol":"Config","kind":"type","lang":"rust","doc":"options. The configuration can be used to build a \"configured\" HIR expression. A configured HIR expression is an HIR expression that is aware of the configuration which generated it, and provides transformation on that HIR such that the configuration is preserved.","code":"pub(crate) struct Config {\n pub(crate) case_insensitive: bool,\n pub(crate) case_smart: bool,\n pub(crate) multi_line: bool,\n pub(crate) dot_matches_new_line: bool,\n pub(crate) swap_greed: bool,\n pub(crate) ignore_whitespace: bool,\n pub(crate) unicode: bool,\n pub(crate) octal: bool,\n pub(crate) size_limit: usize,\n pub(crate) dfa_size_limit: usize,\n pub(crate) nest_limit: u32,\n pub(crate) line_terminator: Option,\n pub(crate) ban: Option,\n pub(crate) crlf: bool,\n pub(crate) word: bool,\n pub(crate) fixed_strings: bool,\n pub(crate) whole_line: bool,\n}"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":46,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n case_insensitive: false,\n case_smart: false,\n multi_line: false,\n dot_matches_new_line: false,\n swap_greed: false,\n ignore_whitespace: false,\n unicode: true,\n octal: false,\n // These size limits are much bigger than what's in the regex\n // crate by default.\n size_limit: 100 * (1 << 20),\n dfa_size_limit: 1000 * (1 << 20),\n nest_limit: 250,\n line_terminator: None,\n ban: None,\n crlf: false,\n word: false,\n fixed_strings: false,\n whole_line: false,\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":75,"symbol":"build_many","kind":"function","lang":"rust","doc":"Use this configuration to build an HIR from the given patterns. The HIR returned corresponds to a single regex that is an alternation of the patterns given.","code":"pub(crate) fn build_many>(\n &self,\n patterns: &[P],\n ) -> Result {\n ConfiguredHIR::new(self.clone(), patterns)\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":84,"symbol":"is_case_insensitive","kind":"function","lang":"rust","doc":"Accounting for the `smart_case` config knob, return true if and only if this pattern should be matched case insensitively.","code":"fn is_case_insensitive(&self, analysis: &AstAnalysis) -> bool {\n if self.case_insensitive {\n return true;\n }\n if !self.case_smart {\n return false;\n }\n analysis.any_literal() && !analysis.any_uppercase()\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":102,"symbol":"is_fixed_strings","kind":"function","lang":"rust","doc":"in that if the knob is false, this will still return true in some cases if the patterns are themselves indistinguishable from literals. The main idea here is that if this returns true, then it is safe to build an `regex_syntax::hir::Hir` value directly from the given patterns as an alternation of `hir::Literal` values.","code":"fn is_fixed_strings>(&self, patterns: &[P]) -> bool {\n // When these are enabled, we really need to parse the patterns and\n // let them go through the standard HIR translation process in order\n // for case folding transforms to be applied.\n if self.case_insensitive || self.case_smart {\n return false;\n }\n // Even if whole_line or word is enabled, both of those things can\n // be implemented by wrapping the Hir generated by an alternation of\n // fixed string literals. So for here at least, we don't care about the\n // word or whole_line settings.\n if self.fixed_strings {\n // ... but if any literal contains a line terminator, then we've\n // got to bail out because this will ultimately result in an error.\n if let Some(lineterm) = self.line_terminator {\n for p in patterns.iter() {\n if has_line_terminator(lineterm, p.as_ref()) {\n return false;\n }\n }\n }\n return true;\n }\n // In this case, the only way we can hand construct the Hir is if none"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":158,"symbol":"ConfiguredHIR","kind":"type","lang":"rust","doc":"that preserves the configuration. For example, the `fast_line_regex` method will apply literal extraction to the inner HIR and use that to build a new regex that matches the extracted literals in a way that is consistent with the configuration that produced this HIR. For example, the size limits set on the configured HIR will be propagated out to any subsequently constructed HIR or regular expression.","code":"pub(crate) struct ConfiguredHIR {\n config: Config,\n hir: Hir,\n}"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":166,"symbol":"new","kind":"function","lang":"rust","doc":"Parse the given patterns into a single HIR expression that represents an alternation of the patterns given.","code":"fn new>(\n config: Config,\n patterns: &[P],\n ) -> Result {\n let hir = if config.is_fixed_strings(patterns) {\n let mut alts = vec![];\n for p in patterns.iter() {\n alts.push(Hir::literal(p.as_ref().as_bytes()));\n }\n log::debug!(\n \"assembling HIR from {} fixed string literals\",\n alts.len()\n );\n let hir = Hir::alternation(alts);\n hir\n } else {\n let mut alts = vec![];\n for p in patterns.iter() {\n alts.push(if config.fixed_strings {\n format!(\"(?:{})\", regex_syntax::escape(p.as_ref()))\n } else {\n format!(\"(?:{})\", p.as_ref())\n });\n }\n let pattern = alts.join(\"|\");\n let ast = ast::parse::ParserBuilder::new()\n .nest_limit(config.nest_limit)\n .octal(config.octal)\n .ignore_whitespace(config.ignore_whitespace)\n .build()\n .parse(&pattern)\n .map_err(Error::generic)?;\n let anal"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":232,"symbol":"config","kind":"function","lang":"rust","doc":"Return a reference to the underlying configuration.","code":"pub(crate) fn config(&self) -> &Config {\n &self.config\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":237,"symbol":"hir","kind":"function","lang":"rust","doc":"Return a reference to the underlying HIR.","code":"pub(crate) fn hir(&self) -> &Hir {\n &self.hir\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":242,"symbol":"to_regex","kind":"function","lang":"rust","doc":"Convert this HIR to a regex that can be used for matching.","code":"pub(crate) fn to_regex(&self) -> Result {\n let meta = Regex::config()\n .utf8_empty(false)\n .nfa_size_limit(Some(self.config.size_limit))\n // We don't expose a knob for this because the one-pass DFA is\n // usually not a perf bottleneck for ripgrep. But we give it some\n // extra room than the default.\n .onepass_size_limit(Some(10 * (1 << 20)))\n // Same deal here. The default limit for full DFAs is VERY small,\n // but with ripgrep we can afford to spend a bit more time on\n // building them I think.\n .dfa_size_limit(Some(1 * (1 << 20)))\n .dfa_state_limit(Some(1_000))\n .hybrid_cache_capacity(self.config.dfa_size_limit);\n Regex::builder()\n .configure(meta)\n .build_from_hir(&self.hir)\n .map_err(Error::regex)\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":263,"symbol":"non_matching_bytes","kind":"function","lang":"rust","doc":"Compute the set of non-matching bytes for this HIR expression.","code":"pub(crate) fn non_matching_bytes(&self) -> ByteSet {\n non_matching_bytes(&self.hir)\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":296,"symbol":"line_terminator","kind":"function","lang":"rust","doc":"multiple lines despite multi-line search being requested, we can still do the faster and more flexible line-by-line search. This is why the non-matching extraction routine removes `\\n` when `\\A` and `\\z` are present even though that's not quite correct... See: ","code":"pub(crate) fn line_terminator(&self) -> Option {\n if self.hir.properties().look_set().contains_anchor_haystack() {\n None\n } else {\n self.config.line_terminator\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":306,"symbol":"into_whole_line","kind":"function","lang":"rust","doc":"Turns this configured HIR into an equivalent one, but where it must match at the start and end of a line.","code":"pub(crate) fn into_whole_line(self) -> ConfiguredHIR {\n let line_anchor_start = Hir::look(self.line_anchor_start());\n let line_anchor_end = Hir::look(self.line_anchor_end());\n let hir =\n Hir::concat(vec![line_anchor_start, self.hir, line_anchor_end]);\n ConfiguredHIR { config: self.config, hir }\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":316,"symbol":"into_word","kind":"function","lang":"rust","doc":"Turns this configured HIR into an equivalent one, but where it must match at word boundaries.","code":"pub(crate) fn into_word(self) -> ConfiguredHIR {\n let hir = Hir::concat(vec![\n Hir::look(if self.config.unicode {\n hir::Look::WordStartHalfUnicode\n } else {\n hir::Look::WordStartHalfAscii\n }),\n self.hir,\n Hir::look(if self.config.unicode {\n hir::Look::WordEndHalfUnicode\n } else {\n hir::Look::WordEndHalfAscii\n }),\n ]);\n ConfiguredHIR { config: self.config, hir }\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":334,"symbol":"line_anchor_start","kind":"function","lang":"rust","doc":"Returns the \"start line\" anchor for this configuration.","code":"fn line_anchor_start(&self) -> hir::Look {\n if self.config.crlf {\n hir::Look::StartCRLF\n } else {\n hir::Look::StartLF\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":343,"symbol":"line_anchor_end","kind":"function","lang":"rust","doc":"Returns the \"end line\" anchor for this configuration.","code":"fn line_anchor_end(&self) -> hir::Look {\n if self.config.crlf { hir::Look::EndCRLF } else { hir::Look::EndLF }\n }"} {"repo":"ripgrep","file":"crates/regex/src/config.rs","line":350,"symbol":"has_line_terminator","kind":"function","lang":"rust","doc":"Returns true if the given literal string contains any byte from the line terminator given.","code":"fn has_line_terminator(lineterm: LineTerminator, literal: &str) -> bool {\n if lineterm.is_crlf() {\n literal.as_bytes().iter().copied().any(|b| b == b'\\r' || b == b'\\n')\n } else {\n literal.as_bytes().iter().copied().any(|b| b == lineterm.as_byte())\n }\n}"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":7,"symbol":"Error","kind":"type","lang":"rust","doc":"An error that can occur in this crate. Generally, this error corresponds to problems building a regular expression, whether it's in parsing, compilation or a problem with guaranteeing a configured optimization.","code":"pub struct Error {\n kind: ErrorKind,\n}"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":12,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(kind: ErrorKind) -> Error {\n Error { kind }\n }"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":16,"symbol":"regex","kind":"function","lang":"rust","code":"pub(crate) fn regex(err: regex_automata::meta::BuildError) -> Error {\n if let Some(size_limit) = err.size_limit() {\n let kind = ErrorKind::Regex(format!(\n \"compiled regex exceeds size limit of {size_limit}\",\n ));\n Error { kind }\n } else if let Some(ref err) = err.syntax_error() {\n Error::generic(err)\n } else {\n Error::generic(err)\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":29,"symbol":"generic","kind":"function","lang":"rust","code":"pub(crate) fn generic(err: E) -> Error {\n Error { kind: ErrorKind::Regex(err.to_string()) }\n }"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":34,"symbol":"kind","kind":"function","lang":"rust","doc":"Return the kind of this error.","code":"pub fn kind(&self) -> &ErrorKind {\n &self.kind\n }"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":42,"symbol":"ErrorKind","kind":"type","lang":"rust","doc":"The kind of an error that can occur.","code":"pub enum ErrorKind {\n /// An error that occurred as a result of parsing a regular expression.\n /// This can be a syntax error or an error that results from attempting to\n /// compile a regular expression that is too big.\n ///\n /// The string here is the underlying error converted to a string.\n Regex(String),\n /// An error that occurs when a building a regex that isn't permitted to\n /// match a line terminator. In general, building the regex will do its\n /// best to make matching a line terminator impossible (e.g., by removing\n /// `\\n` from the `\\s` character class), but if the regex contains a\n /// `\\n` literal, then there is no reasonable choice that can be made and\n /// therefore an error is reported.\n ///\n /// The string is the literal sequence found in the regex that is not\n /// allowed.\n NotAllowed(String),\n /// This error occurs when a non-ASCII line terminator was provided.\n ///\n /// The invalid byte is included in this error.\n InvalidLineTerminator(u8),\n /// Occurs when a banned byte was found in a pattern.\n Banned(u8),\n}"} {"repo":"ripgrep","file":"crates/regex/src/error.rs","line":70,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {\n use bstr::ByteSlice;\n\n match self.kind {\n ErrorKind::Regex(ref s) => write!(f, \"{}\", s),\n ErrorKind::NotAllowed(ref lit) => {\n write!(f, \"the literal {:?} is not allowed in a regex\", lit)\n }\n ErrorKind::InvalidLineTerminator(byte) => {\n write!(\n f,\n \"line terminators must be ASCII, but {byte:?} is not\",\n byte = [byte].as_bstr(),\n )\n }\n ErrorKind::Banned(byte) => {\n write!(\n f,\n \"pattern contains {byte:?} but it is impossible to match\",\n byte = [byte].as_bstr(),\n )\n }\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":40,"symbol":"InnerLiterals","kind":"type","lang":"rust","doc":"in particular is what inhibits the regex engine's own inner literal optimizations from kicking in. This particular regex also did not have any inner literals extracted in the old implementation (ripgrep <=13). So this particular implementation represents a strict improvement from both the old implementation and from the regex engine's own optimizations. (Which could in theory be improved still.)","code":"pub(crate) struct InnerLiterals {\n seq: Seq,\n}"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":54,"symbol":"new","kind":"function","lang":"rust","doc":"extract literals because the inner literal optimization may not be valid. Note that this requires the actual regex that will be used for a search because it will query some state about the compiled regex. That state may influence inner literal extraction.","code":"pub(crate) fn new(chir: &ConfiguredHIR, re: &Regex) -> InnerLiterals {\n // If there's no line terminator, then the inner literal optimization\n // at this level is not valid.\n if chir.config().line_terminator.is_none() {\n log::trace!(\n \"skipping inner literal extraction, \\\n no line terminator is set\"\n );\n return InnerLiterals::none();\n }\n // If we believe the regex is already accelerated, then just let\n // the regex engine do its thing. We'll skip the inner literal\n // optimization.\n //\n // ... but only if the regex doesn't have any Unicode word boundaries.\n // If it does, there's enough of a chance of the regex engine falling\n // back to a slower engine that it's worth trying our own inner literal\n // optimization.\n if re.is_accelerated() {\n if !chir.hir().properties().look_set().contains_word_unicode() {\n log::trace!(\n \"skipping inner literal extraction, \\\n existing regex is believed to already be accelerated\",\n );\n return InnerLiteral"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":96,"symbol":"none","kind":"function","lang":"rust","doc":"Returns a infinite set of inner literals, such that it can never produce a matcher.","code":"pub(crate) fn none() -> InnerLiterals {\n InnerLiterals { seq: Seq::infinite() }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":106,"symbol":"one_regex","kind":"function","lang":"rust","doc":"If it is deemed advantageous to do so (via various suspicious heuristics), this will return a single regular expression pattern that matches a subset of the language matched by the regular expression that generated these literal sets. The idea here is that the pattern returned by this method is much cheaper to search for. i.e., It is usually a single literal or an alternation of literals.","code":"pub(crate) fn one_regex(&self) -> Result, Error> {\n let Some(lits) = self.seq.literals() else { return Ok(None) };\n if lits.is_empty() {\n return Ok(None);\n }\n let mut alts = vec![];\n for lit in lits.iter() {\n alts.push(Hir::literal(lit.as_bytes()));\n }\n let hir = Hir::alternation(alts);\n log::debug!(\"extracted fast line regex: {:?}\", hir.to_string());\n let re = Regex::builder()\n .configure(Regex::config().utf8_empty(false))\n .build_from_hir(&hir)\n .map_err(Error::regex)?;\n Ok(Some(re))\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":131,"symbol":"Extractor","kind":"type","lang":"rust","doc":"An inner literal extractor. This is a somewhat stripped down version of the extractor from regex-syntax. The main difference is that we try to identify a \"best\" set of required literals while traversing the HIR.","code":"struct Extractor {\n limit_class: usize,\n limit_repeat: usize,\n limit_literal_len: usize,\n limit_total: usize,\n}"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":140,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new inner literal extractor with a default configuration.","code":"fn new() -> Extractor {\n Extractor {\n limit_class: 10,\n limit_repeat: 10,\n limit_literal_len: 100,\n limit_total: 64,\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":151,"symbol":"extract_untagged","kind":"function","lang":"rust","doc":"Execute the extractor at the top-level and return an untagged sequence of literals.","code":"fn extract_untagged(&self, hir: &Hir) -> Seq {\n let mut seq = self.extract(hir);\n log::trace!(\"extracted inner literals: {:?}\", seq.seq);\n seq.seq.optimize_for_prefix_by_preference();\n log::trace!(\n \"extracted inner literals after optimization: {:?}\",\n seq.seq\n );\n if !seq.is_good() {\n log::trace!(\n \"throwing away inner literals because they might be slow\"\n );\n seq.make_infinite();\n }\n seq.seq\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":169,"symbol":"extract","kind":"function","lang":"rust","doc":"Execute the extractor and return a sequence of literals.","code":"fn extract(&self, hir: &Hir) -> TSeq {\n use regex_syntax::hir::HirKind::*;\n\n match *hir.kind() {\n Empty | Look(_) => TSeq::singleton(self::Literal::exact(vec![])),\n Literal(hir::Literal(ref bytes)) => {\n let mut seq =\n TSeq::singleton(self::Literal::exact(bytes.to_vec()));\n self.enforce_literal_len(&mut seq);\n seq\n }\n Class(hir::Class::Unicode(ref cls)) => {\n self.extract_class_unicode(cls)\n }\n Class(hir::Class::Bytes(ref cls)) => self.extract_class_bytes(cls),\n Repetition(ref rep) => self.extract_repetition(rep),\n Capture(hir::Capture { ref sub, .. }) => self.extract(sub),\n Concat(ref hirs) => self.extract_concat(hirs.iter()),\n Alternation(ref hirs) => self.extract_alternation(hirs.iter()),\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":196,"symbol":"extract_concat","kind":"function","lang":"rust","doc":"Extract a sequence from the given concatenation. Sequences from each of the child HIR expressions are combined via cross product. This short circuits once the cross product turns into a sequence containing only inexact literals.","code":"fn extract_concat<'a, I: Iterator>(&self, it: I) -> TSeq {\n let mut seq = TSeq::singleton(self::Literal::exact(vec![]));\n let mut prev: Option = None;\n for hir in it {\n // If every element in the sequence is inexact, then a cross\n // product will always be a no-op. Thus, there is nothing else we\n // can add to it and can quit early. Note that this also includes\n // infinite sequences.\n if seq.is_inexact() {\n // If a concatenation has an empty sequence anywhere, then\n // it's impossible for the concatenantion to ever match. So we\n // can just quit now.\n if seq.is_empty() {\n return seq;\n }\n if seq.is_really_good() {\n return seq;\n }\n prev = Some(match prev {\n None => seq,\n Some(prev) => prev.choose(seq),\n });\n seq = TSeq::singleton(self::Literal::exact(vec![]));\n seq.make_not_prefix();\n }\n // Note that 'cross' also dispatches base"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":231,"symbol":"extract_alternation","kind":"function","lang":"rust","doc":"Extract a sequence from the given alternation. This short circuits once the union turns into an infinite sequence.","code":"fn extract_alternation<'a, I: Iterator>(\n &self,\n it: I,\n ) -> TSeq {\n let mut seq = TSeq::empty();\n for hir in it {\n // Once our 'seq' is infinite, every subsequent union\n // operation on it will itself always result in an\n // infinite sequence. Thus, it can never change and we can\n // short-circuit.\n if !seq.is_finite() {\n break;\n }\n seq = self.union(seq, &mut self.extract(hir));\n }\n seq\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":264,"symbol":"extract_repetition","kind":"function","lang":"rust","doc":"The key here really is making sure we get the 'inexact' vs 'exact' attributes correct on each of the literals we add. For example, the fact that 'a*' gives us an inexact 'a' and an exact empty string means that a regex like 'ab*c' will result in [inexact(ab), exact(ac)] literals being extracted, which might actually be a better prefilter than just 'a'.","code":"fn extract_repetition(&self, rep: &hir::Repetition) -> TSeq {\n let mut subseq = self.extract(&rep.sub);\n match *rep {\n hir::Repetition { min: 0, max, greedy, .. } => {\n // When 'max=1', we can retain exactness, since 'a?' is\n // equivalent to 'a|'. Similarly below, 'a??' is equivalent to\n // '|a'.\n if max != Some(1) {\n subseq.make_inexact();\n }\n let mut empty = TSeq::singleton(Literal::exact(vec![]));\n if !greedy {\n std::mem::swap(&mut subseq, &mut empty);\n }\n self.union(subseq, &mut empty)\n }\n hir::Repetition { min, max: Some(max), .. } if min == max => {\n assert!(min > 0); // handled above\n let limit =\n u32::try_from(self.limit_repeat).unwrap_or(u32::MAX);\n let mut seq = TSeq::singleton(Literal::exact(vec![]));\n for _ in 0..std::cmp::min(min, limit) {\n if seq.is_inexact() {\n break;\n }\n seq = self.cross(seq, "} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":320,"symbol":"extract_class_unicode","kind":"function","lang":"rust","doc":"Convert the given Unicode class into a sequence of literals if the class is small enough. If the class is too big, return an infinite sequence.","code":"fn extract_class_unicode(&self, cls: &hir::ClassUnicode) -> TSeq {\n if self.class_over_limit_unicode(cls) {\n return TSeq::infinite();\n }\n let mut seq = TSeq::empty();\n for r in cls.iter() {\n for ch in r.start()..=r.end() {\n seq.push(Literal::from(ch));\n }\n }\n self.enforce_literal_len(&mut seq);\n seq\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":336,"symbol":"extract_class_bytes","kind":"function","lang":"rust","doc":"Convert the given byte class into a sequence of literals if the class is small enough. If the class is too big, return an infinite sequence.","code":"fn extract_class_bytes(&self, cls: &hir::ClassBytes) -> TSeq {\n if self.class_over_limit_bytes(cls) {\n return TSeq::infinite();\n }\n let mut seq = TSeq::empty();\n for r in cls.iter() {\n for b in r.start()..=r.end() {\n seq.push(Literal::from(b));\n }\n }\n self.enforce_literal_len(&mut seq);\n seq\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":352,"symbol":"class_over_limit_unicode","kind":"function","lang":"rust","doc":"Returns true if the given Unicode class exceeds the configured limits on this extractor.","code":"fn class_over_limit_unicode(&self, cls: &hir::ClassUnicode) -> bool {\n let mut count = 0;\n for r in cls.iter() {\n if count > self.limit_class {\n return true;\n }\n count += r.len();\n }\n count > self.limit_class\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":365,"symbol":"class_over_limit_bytes","kind":"function","lang":"rust","doc":"Returns true if the given byte class exceeds the configured limits on this extractor.","code":"fn class_over_limit_bytes(&self, cls: &hir::ClassBytes) -> bool {\n let mut count = 0;\n for r in cls.iter() {\n if count > self.limit_class {\n return true;\n }\n count += r.len();\n }\n count > self.limit_class\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":379,"symbol":"cross","kind":"function","lang":"rust","doc":"Compute the cross product of the two sequences if the result would be within configured limits. Otherwise, make `seq2` infinite and cross the infinite sequence with `seq1`.","code":"fn cross(&self, mut seq1: TSeq, mut seq2: TSeq) -> TSeq {\n if !seq2.prefix {\n return seq1.choose(seq2);\n }\n if seq1\n .max_cross_len(&seq2)\n .map_or(false, |len| len > self.limit_total)\n {\n seq2.make_infinite();\n }\n seq1.cross_forward(&mut seq2);\n assert!(seq1.len().map_or(true, |x| x <= self.limit_total));\n self.enforce_literal_len(&mut seq1);\n seq1\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":398,"symbol":"union","kind":"function","lang":"rust","doc":"Union the two sequences if the result would be within configured limits. Otherwise, make `seq2` infinite and union the infinite sequence with `seq1`.","code":"fn union(&self, mut seq1: TSeq, seq2: &mut TSeq) -> TSeq {\n if seq1.max_union_len(seq2).map_or(false, |len| len > self.limit_total)\n {\n // We try to trim our literal sequences to see if we can make\n // room for more literals. The idea is that we'd rather trim down\n // literals already in our sequence if it means we can add a few\n // more and retain a finite sequence. Otherwise, we'll union with\n // an infinite sequence and that infects everything and effectively\n // stops literal extraction in its tracks.\n //\n // We do we keep 4 bytes here? Well, it's a bit of an abstraction\n // leakage. Downstream, the literals may wind up getting fed to\n // the Teddy algorithm, which supports searching literals up to\n // length 4. So that's why we pick that number here. Arguably this\n // should be a tuneable parameter, but it seems a little tricky to\n // describe. And I'm still unsure if this is the right way to go\n // about culling literal sequences.\n seq1.keep_first_bytes(4);\n seq2.keep_first_bytes(4);\n "} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":434,"symbol":"enforce_literal_len","kind":"function","lang":"rust","doc":"Applies the literal length limit to the given sequence. If none of the literals in the sequence exceed the limit, then this is a no-op.","code":"fn enforce_literal_len(&self, seq: &mut TSeq) {\n seq.keep_first_bytes(self.limit_literal_len);\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":440,"symbol":"TSeq","kind":"type","lang":"rust","code":"struct TSeq {\n seq: Seq,\n prefix: bool,\n}"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":447,"symbol":"empty","kind":"function","lang":"rust","code":"fn empty() -> TSeq {\n TSeq { seq: Seq::empty(), prefix: true }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":451,"symbol":"infinite","kind":"function","lang":"rust","code":"fn infinite() -> TSeq {\n TSeq { seq: Seq::infinite(), prefix: true }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":455,"symbol":"singleton","kind":"function","lang":"rust","code":"fn singleton(lit: Literal) -> TSeq {\n TSeq { seq: Seq::singleton(lit), prefix: true }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":459,"symbol":"new","kind":"function","lang":"rust","code":"fn new(it: I) -> TSeq\n where\n I: IntoIterator,\n B: AsRef<[u8]>,\n {\n TSeq { seq: Seq::new(it), prefix: true }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":467,"symbol":"literals","kind":"function","lang":"rust","code":"fn literals(&self) -> Option<&[Literal]> {\n self.seq.literals()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":471,"symbol":"push","kind":"function","lang":"rust","code":"fn push(&mut self, lit: Literal) {\n self.seq.push(lit);\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":475,"symbol":"make_inexact","kind":"function","lang":"rust","code":"fn make_inexact(&mut self) {\n self.seq.make_inexact();\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":479,"symbol":"make_infinite","kind":"function","lang":"rust","code":"fn make_infinite(&mut self) {\n self.seq.make_infinite();\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":483,"symbol":"cross_forward","kind":"function","lang":"rust","code":"fn cross_forward(&mut self, other: &mut TSeq) {\n assert!(other.prefix);\n self.seq.cross_forward(&mut other.seq);\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":488,"symbol":"union","kind":"function","lang":"rust","code":"fn union(&mut self, other: &mut TSeq) {\n self.seq.union(&mut other.seq);\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":492,"symbol":"dedup","kind":"function","lang":"rust","code":"fn dedup(&mut self) {\n self.seq.dedup();\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":496,"symbol":"sort","kind":"function","lang":"rust","code":"fn sort(&mut self) {\n self.seq.sort();\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":500,"symbol":"keep_first_bytes","kind":"function","lang":"rust","code":"fn keep_first_bytes(&mut self, len: usize) {\n self.seq.keep_first_bytes(len);\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":504,"symbol":"is_finite","kind":"function","lang":"rust","code":"fn is_finite(&self) -> bool {\n self.seq.is_finite()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":508,"symbol":"is_empty","kind":"function","lang":"rust","code":"fn is_empty(&self) -> bool {\n self.seq.is_empty()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":512,"symbol":"len","kind":"function","lang":"rust","code":"fn len(&self) -> Option {\n self.seq.len()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":516,"symbol":"is_exact","kind":"function","lang":"rust","code":"fn is_exact(&self) -> bool {\n self.seq.is_exact()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":520,"symbol":"is_inexact","kind":"function","lang":"rust","code":"fn is_inexact(&self) -> bool {\n self.seq.is_inexact()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":524,"symbol":"max_union_len","kind":"function","lang":"rust","code":"fn max_union_len(&self, other: &TSeq) -> Option {\n self.seq.max_union_len(&other.seq)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":528,"symbol":"max_cross_len","kind":"function","lang":"rust","code":"fn max_cross_len(&self, other: &TSeq) -> Option {\n assert!(other.prefix);\n self.seq.max_cross_len(&other.seq)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":533,"symbol":"min_literal_len","kind":"function","lang":"rust","code":"fn min_literal_len(&self) -> Option {\n self.seq.min_literal_len()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":537,"symbol":"max_literal_len","kind":"function","lang":"rust","code":"fn max_literal_len(&self) -> Option {\n self.seq.max_literal_len()\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":546,"symbol":"make_not_prefix","kind":"function","lang":"rust","doc":"Tags this sequence as \"not a prefix.\" When this happens, this sequence can't be crossed as a suffix of another sequence.","code":"fn make_not_prefix(&mut self) {\n self.prefix = false;\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":553,"symbol":"is_good","kind":"function","lang":"rust","doc":"Returns true if it's believed that the sequence given is \"good\" for acceleration. This is useful for determining whether a sequence of literals has any shot of being fast.","code":"fn is_good(&self) -> bool {\n if self.has_poisonous_literal() {\n return false;\n }\n let Some(min) = self.min_literal_len() else { return false };\n let Some(len) = self.len() else { return false };\n // If we have some very short literals, then let's require that our\n // sequence is itself very small.\n if min <= 1 {\n return len <= 3;\n }\n min >= 2 && len <= 64\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":570,"symbol":"is_really_good","kind":"function","lang":"rust","doc":"Returns true if it's believed that the sequence given is \"really good\" for acceleration. This is useful for short circuiting literal extraction.","code":"fn is_really_good(&self) -> bool {\n if self.has_poisonous_literal() {\n return false;\n }\n let Some(min) = self.min_literal_len() else { return false };\n let Some(len) = self.len() else { return false };\n min >= 3 && len <= 8\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":580,"symbol":"has_poisonous_literal","kind":"function","lang":"rust","doc":"Returns true if the given sequence contains a poisonous literal.","code":"fn has_poisonous_literal(&self) -> bool {\n let Some(lits) = self.literals() else { return false };\n lits.iter().any(is_poisonous)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":587,"symbol":"choose","kind":"function","lang":"rust","doc":"Compare the two sequences and return the one that is believed to be best according to a hodge podge of heuristics.","code":"fn choose(self, other: TSeq) -> TSeq {\n let (mut seq1, mut seq2) = (self, other);\n // Whichever one we pick, by virtue of picking one, we choose\n // to not take the other. So we must consider the result inexact.\n seq1.make_inexact();\n seq2.make_inexact();\n\n if !seq1.is_finite() {\n return seq2;\n } else if !seq2.is_finite() {\n return seq1;\n }\n if seq1.has_poisonous_literal() {\n return seq2;\n } else if seq2.has_poisonous_literal() {\n return seq1;\n }\n let Some(min1) = seq1.min_literal_len() else { return seq2 };\n let Some(min2) = seq2.min_literal_len() else { return seq1 };\n if min1 < min2 {\n return seq2;\n } else if min2 < min1 {\n return seq1;\n }\n // OK because we know both sequences are finite, otherwise they wouldn't\n // have a minimum literal length.\n let len1 = seq1.len().unwrap();\n let len2 = seq2.len().unwrap();\n if len1 < len2 {\n return seq2;\n } else if len2 < len1 {\n return seq1;\n }\n // We could do extra stuff like looking at "} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":628,"symbol":"from_iter","kind":"function","lang":"rust","code":"fn from_iter>(it: T) -> TSeq {\n TSeq { seq: Seq::from_iter(it), prefix: true }\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":635,"symbol":"is_poisonous","kind":"function","lang":"rust","doc":"Returns true if it is believe that this literal is likely to match very frequently, and is thus not a good candidate for a prefilter.","code":"fn is_poisonous(lit: &Literal) -> bool {\n use regex_syntax::hir::literal::rank;\n\n lit.is_empty() || (lit.len() == 1 && rank(lit.as_bytes()[0]) >= 250)\n}"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":645,"symbol":"e","kind":"function","lang":"rust","code":"fn e(pattern: impl AsRef) -> Seq {\n let pattern = pattern.as_ref();\n let hir = regex_syntax::ParserBuilder::new()\n .utf8(false)\n .build()\n .parse(pattern)\n .unwrap();\n Extractor::new().extract_untagged(&hir)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":656,"symbol":"E","kind":"function","lang":"rust","code":"fn E(x: &str) -> Literal {\n Literal::exact(x.as_bytes())\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":661,"symbol":"I","kind":"function","lang":"rust","code":"fn I(x: &str) -> Literal {\n Literal::inexact(x.as_bytes())\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":665,"symbol":"seq","kind":"function","lang":"rust","code":"fn seq>(it: I) -> Seq {\n Seq::from_iter(it)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":669,"symbol":"inexact","kind":"function","lang":"rust","code":"fn inexact(it: I) -> Seq\n where\n I: IntoIterator,\n {\n Seq::from_iter(it)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":676,"symbol":"exact","kind":"function","lang":"rust","code":"fn exact, I: IntoIterator>(it: I) -> Seq {\n Seq::new(it)\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":681,"symbol":"various","kind":"function","lang":"rust","code":"fn various() {\n assert_eq!(e(r\"foo\"), seq([E(\"foo\")]));\n assert_eq!(e(r\"[a-z]foo[a-z]\"), seq([I(\"foo\")]));\n assert_eq!(e(r\"[a-z](foo)(bar)[a-z]\"), seq([I(\"foobar\")]));\n assert_eq!(e(r\"[a-z]([a-z]foo)(bar[a-z])[a-z]\"), seq([I(\"foo\")]));\n assert_eq!(e(r\"[a-z]([a-z]foo)([a-z]foo)[a-z]\"), seq([I(\"foo\")]));\n assert_eq!(e(r\"(\\d{1,3}\\.){3}\\d{1,3}\"), seq([I(\".\")]));\n assert_eq!(e(r\"[a-z]([a-z]foo){3}[a-z]\"), seq([I(\"foo\")]));\n assert_eq!(e(r\"[a-z](foo[a-z]){3}[a-z]\"), seq([I(\"foo\")]));\n assert_eq!(e(r\"[a-z]([a-z]foo[a-z]){3}[a-z]\"), seq([I(\"foo\")]));\n assert_eq!(\n e(r\"[a-z]([a-z]foo){3}(bar[a-z]){3}[a-z]\"),\n seq([I(\"foo\")])\n );\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":700,"symbol":"heuristics","kind":"function","lang":"rust","doc":"These test that some of our suspicious heuristics try to \"pick better literals.\"","code":"fn heuristics() {\n // Here, the first literals we stumble across are {ab, cd, ef}. But we\n // keep going and our heuristics decide that {hiya} is better. (And it\n // should be, since it's just one literal and it's longer.)\n assert_eq!(e(r\"[a-z]+(ab|cd|ef)[a-z]+hiya[a-z]+\"), seq([I(\"hiya\")]));\n // But here, the first alternation becomes \"good enough\" that literal\n // extraction short circuits early. {hiya} is probably still a better\n // choice here, but {abc, def, ghi} is not bad.\n assert_eq!(\n e(r\"[a-z]+(abc|def|ghi)[a-z]+hiya[a-z]+\"),\n seq([I(\"abc\"), I(\"def\"), I(\"ghi\")])\n );\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":715,"symbol":"literal","kind":"function","lang":"rust","code":"fn literal() {\n assert_eq!(exact([\"a\"]), e(\"a\"));\n assert_eq!(exact([\"aaaaa\"]), e(\"aaaaa\"));\n assert_eq!(exact([\"A\", \"a\"]), e(\"(?i-u)a\"));\n assert_eq!(exact([\"AB\", \"Ab\", \"aB\", \"ab\"]), e(\"(?i-u)ab\"));\n assert_eq!(exact([\"abC\", \"abc\"]), e(\"ab(?i-u)c\"));\n\n assert_eq!(Seq::infinite(), e(r\"(?-u:\\xFF)\"));\n assert_eq!(exact([b\"Z\"]), e(r\"Z\"));\n\n assert_eq!(exact([\"☃\"]), e(\"☃\"));\n assert_eq!(exact([\"☃\"]), e(\"(?i)☃\"));\n assert_eq!(exact([\"☃☃☃☃☃\"]), e(\"☃☃☃☃☃\"));\n\n assert_eq!(exact([\"Δ\"]), e(\"Δ\"));\n assert_eq!(exact([\"δ\"]), e(\"δ\"));\n assert_eq!(exact([\"Δ\", \"δ\"]), e(\"(?i)Δ\"));\n assert_eq!(exact([\"Δ\", \"δ\"]), e(\"(?i)δ\"));\n\n assert_eq!(exact([\"S\", \"s\", \"ſ\"]), e(\"(?i)S\"));\n assert_eq!(exact([\"S\", \"s\", \"ſ\"]), e(\"(?i)s\"));\n assert_eq!(exact([\"S\", \"s\", \"ſ\"]), e(\"(?i)ſ\"));\n\n let letters = \"ͱͳͷΐάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋ\";\n assert_eq!(exact([letters]), e(letters));\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":743,"symbol":"class","kind":"function","lang":"rust","code":"fn class() {\n assert_eq!(exact([\"a\", \"b\", \"c\"]), e(\"[abc]\"));\n assert_eq!(exact([\"a1b\", \"a2b\", \"a3b\"]), e(\"a[123]b\"));\n assert_eq!(exact([\"δ\", \"ε\"]), e(\"[εδ]\"));\n assert_eq!(exact([\"Δ\", \"Ε\", \"δ\", \"ε\", \"ϵ\"]), e(r\"(?i)[εδ]\"));\n }"} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":751,"symbol":"look","kind":"function","lang":"rust","code":"fn look() {\n assert_eq!(exact([\"ab\"]), e(r\"a\\Ab\"));\n assert_eq!(exact([\"ab\"]), e(r\"a\\zb\"));\n assert_eq!(exact([\"ab\"]), e(r\"a(?m:^)b\"));\n assert_eq!(exact([\"ab\"]), e(r\"a(?m:$)b\"));\n assert_eq!(exact([\"ab\"]), e(r\"a\\bb\"));\n assert_eq!(exact([\"ab\"]), e(r\"a\\Bb\"));\n assert_eq!(exact([\"ab\"]), e(r\"a(?-u:\\b)b\"));\n assert_eq!(exact([\"ab\"]), e(r\"a(?-u:\\B)b\"));\n\n assert_eq!(exact([\"ab\"]), e(r\"^ab\"));\n assert_eq!(exact([\"ab\"]), e(r\"$ab\"));\n assert_eq!(exact([\"ab\"]), e(r\"(?m:^)ab\"));\n assert_eq!(exact([\"ab\"]), e(r\"(?m:$)ab\"));\n assert_eq!(exact([\"ab\"]), e(r\"\\bab\"));\n assert_eq!(exact([\"ab\"]), e(r\"\\Bab\"));\n assert_eq!(exact([\"ab\"]), e(r\"(?-u:\\b)ab\"));\n assert_eq!(exact([\"ab\"]), e(r\"(?-u:\\B)ab\"));\n\n assert_eq!(exact([\"ab\"]), e(r\"ab^\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab$\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab(?m:^)\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab(?m:$)\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab\\b\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab\\B\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab(?-u:\\b)\"));\n assert_eq!(exact([\"ab\"]), e(r\"ab(?-u:\\B)\"));\n\n "} {"repo":"ripgrep","file":"crates/regex/src/literal.rs","line":783,"symbol":"repetition","kind":"function","lang":"rust","code":"fn repetition() {\n assert_eq!(Seq::infinite(), e(r\"a?\"));\n assert_eq!(Seq::infinite(), e(r\"a??\"));\n assert_eq!(Seq::infinite(), e(r\"a*\"));\n assert_eq!(Seq::infinite(), e(r\"a*?\"));\n assert_eq!(inexact([I(\"a\")]), e(r\"a+\"));\n assert_eq!(inexact([I(\"a\")]), e(r\"(a+)+\"));\n\n assert_eq!(exact([\"ab\"]), e(r\"aZ{0}b\"));\n assert_eq!(exact([\"aZb\", \"ab\"]), e(r\"aZ?b\"));\n assert_eq!(exact([\"ab\", \"aZb\"]), e(r\"aZ??b\"));\n assert_eq!(inexact([I(\"aZ\"), E(\"ab\")]), e(r\"aZ*b\"));\n assert_eq!(inexact([E(\"ab\"), I(\"aZ\")]), e(r\"aZ*?b\"));\n assert_eq!(inexact([I(\"aZ\")]), e(r\"aZ+b\"));\n assert_eq!(inexact([I(\"aZ\")]), e(r\"aZ+?b\"));\n\n assert_eq!(exact([\"aZZb\"]), e(r\"aZ{2}b\"));\n assert_eq!(inexact([I(\"aZZ\")]), e(r\"aZ{2,3}b\"));\n\n assert_eq!(Seq::infinite(), e(r\"(abc)?\"));\n assert_eq!(Seq::infinite(), e(r\"(abc)??\"));\n\n assert_eq!(inexact([I(\"a\"), E(\"b\")]), e(r\"a*b\"));\n assert_eq!(inexact([E(\"b\"), I(\"a\")]), e(r\"a*?b\"));\n assert_eq!(inexact([I(\"ab\")]), e(r\"ab+\"));\n assert_eq!(inexact([I(\"a\"), I(\"b\")]), e(r\"a*b+\"));\n\n assert_eq!(inexact([I(\"a\"), I(\"b\"), E(\"c\")]), e(r\"a*b*"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":24,"symbol":"RegexMatcherBuilder","kind":"type","lang":"rust","doc":"builder, in addition to a few other options such as smart case, word matching and the ability to set a line terminator which may enable certain types of optimizations. The syntax supported is documented as part of the regex crate: .","code":"pub struct RegexMatcherBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":29,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> RegexMatcherBuilder {\n RegexMatcherBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":36,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for configuring a regex matcher.","code":"pub fn new() -> RegexMatcherBuilder {\n RegexMatcherBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":45,"symbol":"build","kind":"function","lang":"rust","doc":"Build a new matcher using the current configuration for the provided pattern. The syntax supported is documented as part of the regex crate: .","code":"pub fn build(&self, pattern: &str) -> Result {\n self.build_many(&[pattern])\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":53,"symbol":"build_many","kind":"function","lang":"rust","doc":"Build a new matcher using the current configuration for the provided patterns. The resulting matcher behaves as if all of the patterns given are joined together into a single alternation. That is, it reports matches where at least one of the given patterns matches.","code":"pub fn build_many>(\n &self,\n patterns: &[P],\n ) -> Result {\n let mut chir = self.config.build_many(patterns)?;\n // 'whole_line' is a strict subset of 'word', so when it is enabled,\n // we don't need to both with any specific to word matching.\n if chir.config().whole_line {\n chir = chir.into_whole_line();\n } else if chir.config().word {\n chir = chir.into_word();\n }\n let regex = chir.to_regex()?;\n log::trace!(\"final regex: {:?}\", chir.hir().to_string());\n\n let non_matching_bytes = chir.non_matching_bytes();\n // If we can pick out some literals from the regex, then we might be\n // able to build a faster regex that quickly identifies candidate\n // matching lines. The regex engine will do what it can on its own, but\n // we can specifically do a little more when a line terminator is set.\n // For example, for a regex like `\\w+foo\\w+`, we can look for `foo`,\n // and when a match is found, look for the line containing `foo` and\n // then run the original regex on only that line. (In this case, the\n // "} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":92,"symbol":"build_literals","kind":"function","lang":"rust","doc":"Build a new matcher from a plain alternation of literals. Depending on the configuration set by the builder, this may be able to build a matcher substantially faster than by joining the patterns with a `|` and calling `build`.","code":"pub fn build_literals>(\n &self,\n literals: &[B],\n ) -> Result {\n self.build_many(literals)\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":103,"symbol":"case_insensitive","kind":"function","lang":"rust","doc":"Set the value for the case insensitive (`i`) flag. When enabled, letters in the pattern will match both upper case and lower case variants.","code":"pub fn case_insensitive(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.case_insensitive = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":120,"symbol":"case_smart","kind":"function","lang":"rust","doc":"1. The pattern contains at least one literal character. For example, `a\\w` contains a literal (`a`) but `\\w` does not. 2. Of the literals in the pattern, none of them are considered to be uppercase according to Unicode. For example, `foo\\pL` has no uppercase literals but `Foo\\pL` does.","code":"pub fn case_smart(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.case_smart = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":131,"symbol":"multi_line","kind":"function","lang":"rust","doc":"Set the value for the multi-line matching (`m`) flag. When enabled, `^` matches the beginning of lines and `$` matches the end of lines. By default, they match beginning/end of the input.","code":"pub fn multi_line(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.multi_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":143,"symbol":"dot_matches_new_line","kind":"function","lang":"rust","doc":"anything when `s` is set and matches anything except for new line when it is not set (the default). N.B. \"matches anything\" means \"any byte\" when Unicode is disabled and means \"any valid UTF-8 encoding of any Unicode scalar value\" when Unicode is enabled.","code":"pub fn dot_matches_new_line(\n &mut self,\n yes: bool,\n ) -> &mut RegexMatcherBuilder {\n self.config.dot_matches_new_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":157,"symbol":"swap_greed","kind":"function","lang":"rust","doc":"Set the value for the greedy swap (`U`) flag. When enabled, a pattern like `a*` is lazy (tries to find shortest match) and `a*?` is greedy (tries to find longest match). By default, `a*` is greedy and `a*?` is lazy.","code":"pub fn swap_greed(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.swap_greed = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":167,"symbol":"ignore_whitespace","kind":"function","lang":"rust","doc":"Set the value for the ignore whitespace (`x`) flag. When enabled, whitespace such as new lines and spaces will be ignored between expressions of the pattern, and `#` can be used to start a comment until the next new line.","code":"pub fn ignore_whitespace(\n &mut self,\n yes: bool,\n ) -> &mut RegexMatcherBuilder {\n self.config.ignore_whitespace = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":179,"symbol":"unicode","kind":"function","lang":"rust","doc":"Set the value for the Unicode (`u`) flag. Enabled by default. When disabled, character classes such as `\\w` only match ASCII word characters instead of all Unicode word characters.","code":"pub fn unicode(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.unicode = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":199,"symbol":"octal","kind":"function","lang":"rust","doc":"syntax like `\\0` invokes a backreference, which is explicitly unsupported in Rust's regex engine. However, many users expect it to be supported. Therefore, when octal support is disabled, the error message will explicitly mention that backreferences aren't supported. Octal syntax is disabled by default.","code":"pub fn octal(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.octal = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":209,"symbol":"size_limit","kind":"function","lang":"rust","doc":"Set the approximate size limit of the compiled regular expression. This roughly corresponds to the number of bytes occupied by a single compiled program. If the program exceeds this number, then a compilation error is returned.","code":"pub fn size_limit(&mut self, bytes: usize) -> &mut RegexMatcherBuilder {\n self.config.size_limit = bytes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":223,"symbol":"dfa_size_limit","kind":"function","lang":"rust","doc":"use while searching. Note that this is a *per thread* limit. There is no way to set a global limit. In particular, if a regex is used from multiple threads simultaneously, then each thread may use up to the number of bytes specified here.","code":"pub fn dfa_size_limit(\n &mut self,\n bytes: usize,\n ) -> &mut RegexMatcherBuilder {\n self.config.dfa_size_limit = bytes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":256,"symbol":"nest_limit","kind":"function","lang":"rust","doc":"Note that a nest limit of `0` will return a nest limit error for most patterns but not all. For example, a nest limit of `0` permits `a` but not `ab`, since `ab` requires a concatenation, which results in a nest depth of `1`. In general, a nest limit is not something that manifests in an obvious way in the concrete syntax, therefore, it should not be used in a granular way.","code":"pub fn nest_limit(&mut self, limit: u32) -> &mut RegexMatcherBuilder {\n self.config.nest_limit = limit;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":281,"symbol":"line_terminator","kind":"function","lang":"rust","doc":"match `a\\nb` (when `\\n` is the line terminator), but the pattern `a\\nb` will result in an error since the `\\n` cannot be easily removed without changing the fundamental intent of the pattern. If the given line terminator isn't an ASCII byte (`<=127`), then the builder will return an error when constructing the matcher.","code":"pub fn line_terminator(\n &mut self,\n line_term: Option,\n ) -> &mut RegexMatcherBuilder {\n self.config.line_terminator = line_term.map(LineTerminator::byte);\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":300,"symbol":"ban_byte","kind":"function","lang":"rust","doc":"This is useful when binary detection is enabled. Callers will likely want to ban the same byte that is used to detect binary data, i.e., the NUL byte. The reason for this is that when binary detection is enabled, it's impossible to match a NUL byte because binary detection will either quit when one is found, or will convert NUL bytes to line terminators to avoid exorbitant heap usage.","code":"pub fn ban_byte(&mut self, byte: Option) -> &mut RegexMatcherBuilder {\n self.config.ban = byte;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":322,"symbol":"crlf","kind":"function","lang":"rust","doc":"Note that if you do not wish to set the line terminator but would still like `$` to match `\\r\\n` line terminators, then it is valid to call `crlf(true)` followed by `line_terminator(None)`. Ordering is important, since `crlf` sets the line terminator, but `line_terminator` does not touch the `crlf` setting.","code":"pub fn crlf(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n if yes {\n self.config.line_terminator = Some(LineTerminator::crlf());\n } else {\n self.config.line_terminator = None;\n }\n self.config.crlf = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":343,"symbol":"word","kind":"function","lang":"rust","doc":"non-word character. This option, in contrast, merely requires that one side match a non-word character. For example, `\\b-2\\b` will not match `foo -2 bar` since `-` is not a word character. However, `-2` with this `word` option enabled will match the `-2` in `foo -2 bar`.","code":"pub fn word(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.word = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":351,"symbol":"fixed_strings","kind":"function","lang":"rust","doc":"Whether the patterns should be treated as literal strings or not. When this is active, all characters, including ones that would normally be special regex meta characters, are matched literally.","code":"pub fn fixed_strings(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.fixed_strings = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":358,"symbol":"whole_line","kind":"function","lang":"rust","doc":"Whether each pattern should match the entire line or not. This is equivalent to surrounding the pattern with `(?m:^)` and `(?m:$)`.","code":"pub fn whole_line(&mut self, yes: bool) -> &mut RegexMatcherBuilder {\n self.config.whole_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":367,"symbol":"RegexMatcher","kind":"type","lang":"rust","doc":"An implementation of the `Matcher` trait using Rust's standard regex library.","code":"pub struct RegexMatcher {\n /// The configuration specified by the caller.\n config: Config,\n /// The regular expression compiled from the pattern provided by the\n /// caller.\n regex: Regex,\n /// A regex that never reports false negatives but may report false\n /// positives that is believed to be capable of being matched more quickly\n /// than `regex`. Typically, this is a single literal or an alternation\n /// of literals.\n fast_line_regex: Option,\n /// A set of bytes that will never appear in a match.\n non_matching_bytes: ByteSet,\n}"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":385,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new matcher from the given pattern using the default configuration.","code":"pub fn new(pattern: &str) -> Result {\n RegexMatcherBuilder::new().build(pattern)\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":401,"symbol":"new_line_matcher","kind":"function","lang":"rust","doc":"`\\n`. The purpose of using this constructor is to permit special optimizations that help speed up line oriented search. These types of optimizations are only appropriate when matches span no more than one line. For this reason, this constructor will return an error if the given pattern contains a literal `\\n`. Other uses of `\\n` (such as in `\\s`) are removed transparently.","code":"pub fn new_line_matcher(pattern: &str) -> Result {\n RegexMatcherBuilder::new().line_terminator(Some(b'\\n')).build(pattern)\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":414,"symbol":"find_at","kind":"function","lang":"rust","code":"fn find_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, NoError> {\n let input = Input::new(haystack).span(at..haystack.len());\n Ok(self.regex.find(input).map(|m| Match::new(m.start(), m.end())))\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":424,"symbol":"new_captures","kind":"function","lang":"rust","code":"fn new_captures(&self) -> Result {\n Ok(RegexCaptures::new(self.regex.create_captures()))\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":429,"symbol":"capture_count","kind":"function","lang":"rust","code":"fn capture_count(&self) -> usize {\n self.regex.captures_len()\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":434,"symbol":"capture_index","kind":"function","lang":"rust","code":"fn capture_index(&self, name: &str) -> Option {\n self.regex.group_info().to_index(PatternID::ZERO, name)\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":439,"symbol":"try_find_iter","kind":"function","lang":"rust","code":"fn try_find_iter(\n &self,\n haystack: &[u8],\n mut matched: F,\n ) -> Result, NoError>\n where\n F: FnMut(Match) -> Result,\n {\n for m in self.regex.find_iter(haystack) {\n match matched(Match::new(m.start(), m.end())) {\n Ok(true) => continue,\n Ok(false) => return Ok(Ok(())),\n Err(err) => return Ok(Err(err)),\n }\n }\n Ok(Ok(()))\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":458,"symbol":"captures_at","kind":"function","lang":"rust","code":"fn captures_at(\n &self,\n haystack: &[u8],\n at: usize,\n caps: &mut RegexCaptures,\n ) -> Result {\n let input = Input::new(haystack).span(at..haystack.len());\n let caps = caps.captures_mut();\n self.regex.search_captures(&input, caps);\n Ok(caps.is_match())\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":471,"symbol":"shortest_match_at","kind":"function","lang":"rust","code":"fn shortest_match_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, NoError> {\n let input = Input::new(haystack).span(at..haystack.len());\n Ok(self.regex.search_half(&input).map(|hm| hm.offset()))\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":481,"symbol":"non_matching_bytes","kind":"function","lang":"rust","code":"fn non_matching_bytes(&self) -> Option<&ByteSet> {\n Some(&self.non_matching_bytes)\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":486,"symbol":"line_terminator","kind":"function","lang":"rust","code":"fn line_terminator(&self) -> Option {\n self.config.line_terminator\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":491,"symbol":"find_candidate_line","kind":"function","lang":"rust","code":"fn find_candidate_line(\n &self,\n haystack: &[u8],\n ) -> Result, NoError> {\n Ok(match self.fast_line_regex {\n Some(ref regex) => {\n let input = Input::new(haystack);\n regex\n .search_half(&input)\n .map(|hm| LineMatchKind::Candidate(hm.offset()))\n }\n None => {\n self.shortest_match(haystack)?.map(LineMatchKind::Confirmed)\n }\n })\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":524,"symbol":"RegexCaptures","kind":"type","lang":"rust","doc":"For example, in the regex, `(?P\\w)|(?P\\W)`, only one of `foo` or `bar` will ever be set in any given match. In order to access a capture group by name, you'll need to first find the index of the group using the corresponding matcher's `capture_index` method, and then use that index with `RegexCaptures::get`.","code":"pub struct RegexCaptures {\n /// Where the captures are stored.\n caps: AutomataCaptures,\n}"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":531,"symbol":"len","kind":"function","lang":"rust","code":"fn len(&self) -> usize {\n self.caps.group_info().all_group_len()\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":536,"symbol":"get","kind":"function","lang":"rust","code":"fn get(&self, i: usize) -> Option {\n self.caps.get_group(i).map(|sp| Match::new(sp.start, sp.end))\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":543,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(caps: AutomataCaptures) -> RegexCaptures {\n RegexCaptures { caps }\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":548,"symbol":"captures_mut","kind":"function","lang":"rust","code":"pub(crate) fn captures_mut(&mut self) -> &mut AutomataCaptures {\n &mut self.caps\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":560,"symbol":"word","kind":"function","lang":"rust","doc":"Test that enabling word matches does the right thing and demonstrate the difference between it and surrounding the regex in `\\b`.","code":"fn word() {\n let matcher =\n RegexMatcherBuilder::new().word(true).build(r\"-2\").unwrap();\n assert!(matcher.is_match(b\"abc -2 foo\").unwrap());\n\n let matcher =\n RegexMatcherBuilder::new().word(false).build(r\"\\b-2\\b\").unwrap();\n assert!(!matcher.is_match(b\"abc -2 foo\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":573,"symbol":"line_terminator","kind":"function","lang":"rust","doc":"Test that enabling a line terminator prevents it from matching through said line terminator.","code":"fn line_terminator() {\n // This works, because there's no line terminator specified.\n let matcher = RegexMatcherBuilder::new().build(r\"abc\\sxyz\").unwrap();\n assert!(matcher.is_match(b\"abc\\nxyz\").unwrap());\n\n // This doesn't.\n let matcher = RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"abc\\sxyz\")\n .unwrap();\n assert!(!matcher.is_match(b\"abc\\nxyz\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":589,"symbol":"line_terminator_error","kind":"function","lang":"rust","doc":"Ensure that the builder returns an error if a line terminator is set and the regex could not be modified to remove a line terminator.","code":"fn line_terminator_error() {\n assert!(\n RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"a\\nz\")\n .is_err()\n )\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":600,"symbol":"line_terminator_crlf","kind":"function","lang":"rust","doc":"Test that enabling CRLF permits `$` to match at the end of a line.","code":"fn line_terminator_crlf() {\n // Test normal use of `$` with a `\\n` line terminator.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(matcher.is_match(b\"abc\\n\").unwrap());\n\n // Test that `$` doesn't match at `\\r\\n` boundary normally.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(!matcher.is_match(b\"abc\\r\\n\").unwrap());\n\n // Now check the CRLF handling.\n let matcher = RegexMatcherBuilder::new()\n .multi_line(true)\n .crlf(true)\n .build(r\"abc$\")\n .unwrap();\n assert!(matcher.is_match(b\"abc\\r\\n\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":626,"symbol":"case_smart","kind":"function","lang":"rust","doc":"Test that smart case works.","code":"fn case_smart() {\n let matcher =\n RegexMatcherBuilder::new().case_smart(true).build(r\"abc\").unwrap();\n assert!(matcher.is_match(b\"ABC\").unwrap());\n\n let matcher =\n RegexMatcherBuilder::new().case_smart(true).build(r\"aBc\").unwrap();\n assert!(!matcher.is_match(b\"ABC\").unwrap());\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":640,"symbol":"candidate_lines","kind":"function","lang":"rust","doc":"Test that finding candidate lines works as expected. FIXME: Re-enable this test once inner literal extraction works.","code":"fn candidate_lines() {\n fn is_confirmed(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Confirmed(_) => true,\n _ => false,\n }\n }\n fn is_candidate(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Candidate(_) => true,\n _ => false,\n }\n }\n\n // With no line terminator set, we can't employ any optimizations,\n // so we get a confirmed match.\n let matcher = RegexMatcherBuilder::new().build(r\"\\wfoo\\s\").unwrap();\n let m = matcher.find_candidate_line(b\"afoo \").unwrap().unwrap();\n assert!(is_confirmed(m));\n\n // With a line terminator and a regex specially crafted to have an\n // easy-to-detect inner literal, we can apply an optimization that\n // quickly finds candidate matches.\n let matcher = RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"\\wfoo\\s\")\n .unwrap();\n let m = matcher.find_candidate_line(b\"afoo \").unwrap().unwrap();\n assert!(is_candidate(m));\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":641,"symbol":"is_confirmed","kind":"function","lang":"rust","code":"fn is_confirmed(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Confirmed(_) => true,\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/matcher.rs","line":647,"symbol":"is_candidate","kind":"function","lang":"rust","code":"fn is_candidate(m: LineMatchKind) -> bool {\n match m {\n LineMatchKind::Candidate(_) => true,\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":10,"symbol":"non_matching_bytes","kind":"function","lang":"rust","doc":"Return a confirmed set of non-matching bytes from the given expression.","code":"pub(crate) fn non_matching_bytes(expr: &Hir) -> ByteSet {\n let mut set = ByteSet::full();\n remove_matching_bytes(expr, &mut set);\n set\n}"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":18,"symbol":"remove_matching_bytes","kind":"function","lang":"rust","doc":"Remove any bytes from the given set that can occur in a matched produced by the given expression.","code":"fn remove_matching_bytes(expr: &Hir, set: &mut ByteSet) {\n match *expr.kind() {\n HirKind::Empty\n | HirKind::Look(Look::WordAscii | Look::WordAsciiNegate)\n | HirKind::Look(Look::WordUnicode | Look::WordUnicodeNegate)\n | HirKind::Look(Look::WordStartAscii | Look::WordStartUnicode)\n | HirKind::Look(Look::WordEndAscii | Look::WordEndUnicode)\n | HirKind::Look(\n Look::WordStartHalfAscii | Look::WordStartHalfUnicode,\n )\n | HirKind::Look(Look::WordEndHalfAscii | Look::WordEndHalfUnicode) => {\n }\n HirKind::Look(Look::Start | Look::End) => {\n // FIXME: This is wrong, but not doing this leads to incorrect\n // results because of how anchored searches are implemented in\n // the 'grep-searcher' crate.\n set.remove(b'\\n');\n }\n HirKind::Look(Look::StartLF | Look::EndLF) => {\n set.remove(b'\\n');\n }\n HirKind::Look(Look::StartCRLF | Look::EndCRLF) => {\n set.remove(b'\\r');\n set.remove(b'\\n');\n }\n HirKind::Literal(hir::Literal(ref lit)) => {\n for &b in lit.iter() {\n set.remove(b"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":89,"symbol":"extract","kind":"function","lang":"rust","code":"fn extract(pattern: &str) -> ByteSet {\n let expr =\n ParserBuilder::new().utf8(false).build().parse(pattern).unwrap();\n non_matching_bytes(&expr)\n }"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":95,"symbol":"sparse","kind":"function","lang":"rust","code":"fn sparse(set: &ByteSet) -> Vec {\n let mut sparse_set = vec![];\n for b in (0..256).map(|b| b as u8) {\n if set.contains(b) {\n sparse_set.push(b);\n }\n }\n sparse_set\n }"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":105,"symbol":"sparse_except","kind":"function","lang":"rust","code":"fn sparse_except(except: &[u8]) -> Vec {\n let mut except_set = vec![false; 256];\n for &b in except {\n except_set[b as usize] = true;\n }\n\n let mut set = vec![];\n for b in (0..256).map(|b| b as u8) {\n if !except_set[b as usize] {\n set.push(b);\n }\n }\n set\n }"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":121,"symbol":"dot","kind":"function","lang":"rust","code":"fn dot() {\n assert_eq!(\n sparse(&extract(\".\")),\n vec![\n b'\\n', 192, 193, 245, 246, 247, 248, 249, 250, 251, 252, 253,\n 254, 255,\n ]\n );\n assert_eq!(\n sparse(&extract(\"(?s).\")),\n vec![\n 192, 193, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,\n 255,\n ]\n );\n assert_eq!(sparse(&extract(\"(?-u).\")), vec![b'\\n']);\n assert_eq!(sparse(&extract(\"(?s-u).\")), vec![]);\n }"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":141,"symbol":"literal","kind":"function","lang":"rust","code":"fn literal() {\n assert_eq!(sparse(&extract(\"a\")), sparse_except(&[b'a']));\n assert_eq!(sparse(&extract(\"☃\")), sparse_except(&[0xE2, 0x98, 0x83]));\n assert_eq!(sparse(&extract(r\"\\xFF\")), sparse_except(&[0xC3, 0xBF]));\n assert_eq!(sparse(&extract(r\"(?-u)\\xFF\")), sparse_except(&[0xFF]));\n }"} {"repo":"ripgrep","file":"crates/regex/src/non_matching.rs","line":149,"symbol":"anchor","kind":"function","lang":"rust","code":"fn anchor() {\n // FIXME: The first four tests below should correspond to a full set\n // of bytes for the non-matching bytes I think.\n assert_eq!(sparse(&extract(r\"^\")), sparse_except(&[b'\\n']));\n assert_eq!(sparse(&extract(r\"$\")), sparse_except(&[b'\\n']));\n assert_eq!(sparse(&extract(r\"\\A\")), sparse_except(&[b'\\n']));\n assert_eq!(sparse(&extract(r\"\\z\")), sparse_except(&[b'\\n']));\n assert_eq!(sparse(&extract(r\"(?m)^\")), sparse_except(&[b'\\n']));\n assert_eq!(sparse(&extract(r\"(?m)$\")), sparse_except(&[b'\\n']));\n }"} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":39,"symbol":"strip_from_match","kind":"function","lang":"rust","doc":"Consider enabling multiline mode with the --multiline flag (or -U for short). When multiline mode is enabled, new line characters can be matched. ``` This looks like a good error message to me, and even suggests a flag that the user can use instead.","code":"pub(crate) fn strip_from_match(\n expr: Hir,\n line_term: LineTerminator,\n) -> Result {\n if line_term.is_crlf() {\n let expr1 = strip_from_match_ascii(expr, b'\\r')?;\n strip_from_match_ascii(expr1, b'\\n')\n } else {\n strip_from_match_ascii(expr, line_term.as_byte())\n }\n}"} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":55,"symbol":"strip_from_match_ascii","kind":"function","lang":"rust","doc":"The implementation of strip_from_match. The given byte must be ASCII. This function returns an error otherwise. It also returns an error if it couldn't remove `\\n` from the given regex without leaving an empty character class in its place.","code":"fn strip_from_match_ascii(expr: Hir, byte: u8) -> Result {\n if !byte.is_ascii() {\n return Err(Error::new(ErrorKind::InvalidLineTerminator(byte)));\n }\n let ch = char::from(byte);\n let invalid = || Err(Error::new(ErrorKind::NotAllowed(ch.to_string())));\n Ok(match expr.into_kind() {\n HirKind::Empty => Hir::empty(),\n HirKind::Literal(hir::Literal(lit)) => {\n if lit.iter().find(|&&b| b == byte).is_some() {\n return invalid();\n }\n Hir::literal(lit)\n }\n HirKind::Class(hir::Class::Unicode(mut cls)) => {\n if cls.ranges().is_empty() {\n return Ok(Hir::class(hir::Class::Unicode(cls)));\n }\n let remove = hir::ClassUnicode::new(Some(\n hir::ClassUnicodeRange::new(ch, ch),\n ));\n cls.difference(&remove);\n if cls.ranges().is_empty() {\n return invalid();\n }\n Hir::class(hir::Class::Unicode(cls))\n }\n HirKind::Class(hir::Class::Bytes(mut cls)) => {\n if cls.ranges().is_empty() {\n return Ok(Hir::class(hir::Class::Bytes(cls)));\n "} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":128,"symbol":"roundtrip","kind":"function","lang":"rust","code":"fn roundtrip(pattern: &str, byte: u8) -> String {\n roundtrip_line_term(pattern, LineTerminator::byte(byte)).unwrap()\n }"} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":132,"symbol":"roundtrip_crlf","kind":"function","lang":"rust","code":"fn roundtrip_crlf(pattern: &str) -> String {\n roundtrip_line_term(pattern, LineTerminator::crlf()).unwrap()\n }"} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":136,"symbol":"roundtrip_err","kind":"function","lang":"rust","code":"fn roundtrip_err(pattern: &str, byte: u8) -> Result {\n roundtrip_line_term(pattern, LineTerminator::byte(byte))\n }"} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":140,"symbol":"roundtrip_line_term","kind":"function","lang":"rust","code":"fn roundtrip_line_term(\n pattern: &str,\n line_term: LineTerminator,\n ) -> Result {\n let expr1 = Parser::new().parse(pattern).unwrap();\n let expr2 = strip_from_match(expr1, line_term)?;\n Ok(expr2.to_string())\n }"} {"repo":"ripgrep","file":"crates/regex/src/strip.rs","line":150,"symbol":"various","kind":"function","lang":"rust","code":"fn various() {\n assert_eq!(roundtrip(r\"[a\\n]\", b'\\n'), \"a\");\n assert_eq!(roundtrip(r\"[a\\n]\", b'a'), \"\\n\");\n assert_eq!(roundtrip_crlf(r\"[a\\n]\"), \"a\");\n assert_eq!(roundtrip_crlf(r\"[a\\r]\"), \"a\");\n assert_eq!(roundtrip_crlf(r\"[a\\r\\n]\"), \"a\");\n\n assert_eq!(roundtrip(r\"(?-u)\\s\", b'a'), r\"(?-u:[\\x09-\\x0D\\x20])\");\n assert_eq!(roundtrip(r\"(?-u)\\s\", b'\\n'), r\"(?-u:[\\x09\\x0B-\\x0D\\x20])\");\n\n assert!(roundtrip_err(r\"\\n\", b'\\n').is_err());\n assert!(roundtrip_err(r\"abc\\n\", b'\\n').is_err());\n assert!(roundtrip_err(r\"\\nabc\", b'\\n').is_err());\n assert!(roundtrip_err(r\"abc\\nxyz\", b'\\n').is_err());\n assert!(roundtrip_err(r\"\\x0A\", b'\\n').is_err());\n assert!(roundtrip_err(r\"\\u000A\", b'\\n').is_err());\n assert!(roundtrip_err(r\"\\U0000000A\", b'\\n').is_err());\n assert!(roundtrip_err(r\"\\u{A}\", b'\\n').is_err());\n assert!(roundtrip_err(\"\\n\", b'\\n').is_err());\n }"} {"repo":"ripgrep","file":"crates/searcher/examples/search-stdin.rs","line":10,"symbol":"main","kind":"function","lang":"rust","code":"fn main() {\n if let Err(err) = example() {\n eprintln!(\"{}\", err);\n process::exit(1);\n }\n}"} {"repo":"ripgrep","file":"crates/searcher/examples/search-stdin.rs","line":17,"symbol":"example","kind":"function","lang":"rust","code":"fn example() -> Result<(), Box> {\n let pattern = match env::args().nth(1) {\n Some(pattern) => pattern,\n None => {\n return Err(From::from(format!(\"Usage: search-stdin \")));\n }\n };\n let matcher = RegexMatcher::new(&pattern)?;\n Searcher::new().search_reader(\n &matcher,\n io::stdin(),\n UTF8(|lnum, line| {\n print!(\"{}:{}\", lnum, line);\n Ok(true)\n }),\n )?;\n Ok(())\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":17,"symbol":"BufferAllocation","kind":"type","lang":"rust","doc":"When searching data incrementally using a fixed size buffer, this controls the amount of *additional* memory to allocate beyond the size of the buffer to accommodate lines (which may include the lines in a context window, when enabled) that do not fit in the buffer. The default is to eagerly allocate without a limit.","code":"pub(crate) enum BufferAllocation {\n /// Attempt to expand the size of the buffer until either at least the next\n /// line fits into memory or until all available memory is exhausted.\n ///\n /// This is the default.\n Eager,\n /// Limit the amount of additional memory allocated to the given size. If\n /// a line is found that requires more memory than is allowed here, then\n /// stop reading and return an error.\n Error(usize),\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":30,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> BufferAllocation {\n BufferAllocation::Eager\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":37,"symbol":"alloc_error","kind":"function","lang":"rust","doc":"Create a new error to be used when a configured allocation limit has been reached.","code":"pub(crate) fn alloc_error(limit: usize) -> io::Error {\n let msg = format!(\"configured allocation limit ({}) exceeded\", limit);\n io::Error::new(io::ErrorKind::Other, msg)\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":51,"symbol":"BinaryDetection","kind":"type","lang":"rust","doc":"Binary detection is the process of _heuristically_ identifying whether a given chunk of data is binary or not, and then taking an action based on the result of that heuristic. The motivation behind detecting binary data is that binary data often indicates data that is undesirable to search using textual patterns. Of course, there are many cases in which this isn't true, which is why binary detection is disabled by default.","code":"pub(crate) enum BinaryDetection {\n /// No binary detection is performed. Data reported by the line buffer may\n /// contain arbitrary bytes.\n None,\n /// The given byte is searched in all contents read by the line buffer. If\n /// it occurs, then the data is considered binary and the line buffer acts\n /// as if it reached EOF. The line buffer guarantees that this byte will\n /// never be observable by callers.\n Quit(u8),\n /// The given byte is searched in all contents read by the line buffer. If\n /// it occurs, then it is replaced by the line terminator. The line buffer\n /// guarantees that this byte will never be observable by callers.\n Convert(u8),\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":67,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> BinaryDetection {\n BinaryDetection::None\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":75,"symbol":"is_quit","kind":"function","lang":"rust","doc":"Returns true if and only if the detection heuristic demands that the line buffer stop read data once binary data is observed.","code":"fn is_quit(&self) -> bool {\n match *self {\n BinaryDetection::Quit(_) => true,\n _ => false,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":86,"symbol":"Config","kind":"type","lang":"rust","doc":"The configuration of a buffer. This contains options that are fixed once a buffer has been constructed.","code":"struct Config {\n /// The number of bytes to attempt to read at a time.\n capacity: usize,\n /// The line terminator.\n lineterm: u8,\n /// The behavior for handling long lines.\n buffer_alloc: BufferAllocation,\n /// When set, the presence of the given byte indicates binary content.\n binary: BinaryDetection,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":98,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n capacity: DEFAULT_BUFFER_CAPACITY,\n lineterm: b'\\n',\n buffer_alloc: BufferAllocation::default(),\n binary: BinaryDetection::default(),\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":110,"symbol":"LineBufferBuilder","kind":"type","lang":"rust","doc":"A builder for constructing line buffers.","code":"pub(crate) struct LineBufferBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":116,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new builder for a buffer.","code":"pub(crate) fn new() -> LineBufferBuilder {\n LineBufferBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":121,"symbol":"build","kind":"function","lang":"rust","doc":"Create a new line buffer from this builder's configuration.","code":"pub(crate) fn build(&self) -> LineBuffer {\n LineBuffer {\n config: self.config,\n buf: vec![0; self.config.capacity],\n pos: 0,\n last_lineterm: 0,\n end: 0,\n absolute_byte_offset: 0,\n binary_byte_offset: None,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":141,"symbol":"capacity","kind":"function","lang":"rust","doc":"In general, the capacity of a buffer corresponds to the amount of data to hold in memory, and the size of the reads to make to the underlying reader. This is set to a reasonable default and probably shouldn't be changed unless there's a specific reason to do so.","code":"pub(crate) fn capacity(\n &mut self,\n capacity: usize,\n ) -> &mut LineBufferBuilder {\n self.config.capacity = capacity;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":160,"symbol":"line_terminator","kind":"function","lang":"rust","doc":"read is likely to correspond to an incomplete line. As a line buffer, callers should not access this data since it is incomplete. The line terminator is how the line buffer determines the part of the read that is incomplete. By default, this is set to `b'\\n'`.","code":"pub(crate) fn line_terminator(\n &mut self,\n lineterm: u8,\n ) -> &mut LineBufferBuilder {\n self.config.lineterm = lineterm;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":182,"symbol":"buffer_alloc","kind":"function","lang":"rust","doc":"Note that this setting only applies to the amount of *additional* memory to allocate, beyond the capacity of the buffer. That means that a value of `0` is sensible, and in particular, will guarantee that a line buffer will never allocate additional memory beyond its initial capacity.","code":"pub(crate) fn buffer_alloc(\n &mut self,\n behavior: BufferAllocation,\n ) -> &mut LineBufferBuilder {\n self.config.buffer_alloc = behavior;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":196,"symbol":"binary_detection","kind":"function","lang":"rust","doc":"Whether to enable binary detection or not. Depending on the setting, this can either cause the line buffer to report EOF early or it can cause the line buffer to clean the data. By default, this is disabled. In general, binary detection should be viewed as an imperfect heuristic.","code":"pub(crate) fn binary_detection(\n &mut self,\n detection: BinaryDetection,\n ) -> &mut LineBufferBuilder {\n self.config.binary = detection;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":208,"symbol":"LineBufferReader","kind":"type","lang":"rust","doc":"A line buffer reader efficiently reads a line oriented buffer from an arbitrary reader.","code":"pub(crate) struct LineBufferReader<'b, R> {\n rdr: R,\n line_buffer: &'b mut LineBuffer,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":219,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new buffered reader that reads from `rdr` and uses the given `line_buffer` as an intermediate buffer. This does not change the binary detection behavior of the given line buffer.","code":"pub(crate) fn new(\n rdr: R,\n line_buffer: &'b mut LineBuffer,\n ) -> LineBufferReader<'b, R> {\n line_buffer.clear();\n LineBufferReader { rdr, line_buffer }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":233,"symbol":"absolute_byte_offset","kind":"function","lang":"rust","doc":"The absolute byte offset which corresponds to the starting offsets of the data returned by `buffer` relative to the beginning of the underlying reader's contents. As such, this offset does not generally correspond to an offset in memory. It is typically used for reporting purposes. It can also be used for counting the number of bytes that have been searched.","code":"pub(crate) fn absolute_byte_offset(&self) -> u64 {\n self.line_buffer.absolute_byte_offset()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":239,"symbol":"binary_byte_offset","kind":"function","lang":"rust","doc":"If binary data was detected, then this returns the absolute byte offset at which binary data was initially found.","code":"pub(crate) fn binary_byte_offset(&self) -> Option {\n self.line_buffer.binary_byte_offset()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":256,"symbol":"fill","kind":"function","lang":"rust","doc":"`Quit`, then the presence of binary data will cause this buffer to behave as if it had seen EOF at the first occurrence of binary data.) This forwards any errors returned by the underlying reader, and will also return an error if the buffer must be expanded past its allocation limit, as governed by the buffer allocation strategy.","code":"pub(crate) fn fill(&mut self) -> Result {\n self.line_buffer.fill(&mut self.rdr)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":261,"symbol":"buffer","kind":"function","lang":"rust","doc":"Return the contents of this buffer.","code":"pub(crate) fn buffer(&self) -> &[u8] {\n self.line_buffer.buffer()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":268,"symbol":"bstr","kind":"function","lang":"rust","doc":"Return the buffer as a BStr, used for convenient equality checking in tests only.","code":"fn bstr(&self) -> &bstr::BStr {\n self.buffer().as_bstr()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":274,"symbol":"consume","kind":"function","lang":"rust","doc":"Consume the number of bytes provided. This must be less than or equal to the number of bytes returned by `buffer`.","code":"pub(crate) fn consume(&mut self, amt: usize) {\n self.line_buffer.consume(amt);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":283,"symbol":"consume_all","kind":"function","lang":"rust","doc":"Consumes the remainder of the buffer. Subsequent calls to `buffer` are guaranteed to return an empty slice until the buffer is refilled. This is a convenience function for `consume(buffer.len())`.","code":"fn consume_all(&mut self) {\n self.line_buffer.consume_all();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":294,"symbol":"LineBuffer","kind":"type","lang":"rust","doc":"A line buffer manages a (typically fixed) buffer for holding lines. Callers should create line buffers sparingly and reuse them when possible. Line buffers cannot be used directly, but instead must be used via the LineBufferReader.","code":"pub(crate) struct LineBuffer {\n /// The configuration of this buffer.\n config: Config,\n /// The primary buffer with which to hold data.\n buf: Vec,\n /// The current position of this buffer. This is always a valid sliceable\n /// index into `buf`, and its maximum value is the length of `buf`.\n pos: usize,\n /// The end position of searchable content in this buffer. This is either\n /// set to just after the final line terminator in the buffer, or to just\n /// after the end of the last byte emitted by the reader when the reader\n /// has been exhausted.\n last_lineterm: usize,\n /// The end position of the buffer. This is always greater than or equal to\n /// last_lineterm. The bytes between last_lineterm and end, if any, always\n /// correspond to a partial line.\n end: usize,\n /// The absolute byte offset corresponding to `pos`. This is most typically\n /// not a valid index into addressable memory, but rather, an offset that\n /// is relative to all data that passes through a line buffer (since\n /// construction or since the last time `clear` was called).\n ///\n /// When the line buffer reaches EOF, this is set to the positi"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":330,"symbol":"set_binary_detection","kind":"function","lang":"rust","doc":"Set the binary detection method used on this line buffer. This permits dynamically changing the binary detection strategy on an existing line buffer without needing to create a new one.","code":"pub(crate) fn set_binary_detection(&mut self, binary: BinaryDetection) {\n self.config.binary = binary;\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":335,"symbol":"clear","kind":"function","lang":"rust","doc":"Reset this buffer, such that it can be used with a new reader.","code":"fn clear(&mut self) {\n self.pos = 0;\n self.last_lineterm = 0;\n self.end = 0;\n self.absolute_byte_offset = 0;\n self.binary_byte_offset = None;\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":350,"symbol":"absolute_byte_offset","kind":"function","lang":"rust","doc":"of the data returned by `buffer` relative to the beginning of the reader's contents. As such, this offset does not generally correspond to an offset in memory. It is typically used for reporting purposes, particularly in error messages. This is reset to `0` when `clear` is called.","code":"fn absolute_byte_offset(&self) -> u64 {\n self.absolute_byte_offset\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":356,"symbol":"binary_byte_offset","kind":"function","lang":"rust","doc":"If binary data was detected, then this returns the absolute byte offset at which binary data was initially found.","code":"fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":361,"symbol":"buffer","kind":"function","lang":"rust","doc":"Return the contents of this buffer.","code":"fn buffer(&self) -> &[u8] {\n &self.buf[self.pos..self.last_lineterm]\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":367,"symbol":"free_buffer","kind":"function","lang":"rust","doc":"Return the contents of the free space beyond the end of the buffer as a mutable slice.","code":"fn free_buffer(&mut self) -> &mut [u8] {\n &mut self.buf[self.end..]\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":373,"symbol":"consume","kind":"function","lang":"rust","doc":"Consume the number of bytes provided. This must be less than or equal to the number of bytes returned by `buffer`.","code":"fn consume(&mut self, amt: usize) {\n assert!(amt <= self.buffer().len());\n self.pos += amt;\n self.absolute_byte_offset += amt as u64;\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":384,"symbol":"consume_all","kind":"function","lang":"rust","doc":"Consumes the remainder of the buffer. Subsequent calls to `buffer` are guaranteed to return an empty slice until the buffer is refilled. This is a convenience function for `consume(buffer.len())`.","code":"fn consume_all(&mut self) {\n let amt = self.buffer().len();\n self.consume(amt);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":406,"symbol":"fill","kind":"function","lang":"rust","doc":"`Quit`, then the presence of binary data will cause this buffer to behave as if it had seen EOF.) This forwards any errors returned by `rdr`, and will also return an error if the buffer must be expanded past its allocation limit, as governed by the buffer allocation strategy.","code":"fn fill(&mut self, mut rdr: R) -> Result {\n // If the binary detection heuristic tells us to quit once binary data\n // has been observed, then we no longer read new data and reach EOF\n // once the current buffer has been consumed.\n if self.config.binary.is_quit() && self.binary_byte_offset.is_some() {\n return Ok(!self.buffer().is_empty());\n }\n\n self.roll();\n assert_eq!(self.pos, 0);\n loop {\n self.ensure_capacity()?;\n let readlen = rdr.read(self.free_buffer().as_bytes_mut())?;\n if readlen == 0 {\n // We're only done reading for good once the caller has\n // consumed everything.\n self.last_lineterm = self.end;\n return Ok(!self.buffer().is_empty());\n }\n\n // Get a mutable view into the bytes we've just read. These are\n // the bytes that we do binary detection on, and also the bytes we\n // search to find the last line terminator. We need a mutable slice\n // in the case of binary conversion.\n let oldend = self.end;\n self.end +="} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":480,"symbol":"roll","kind":"function","lang":"rust","doc":"Roll the unconsumed parts of the buffer to the front. This operation is idempotent. After rolling, `last_lineterm` and `end` point to the same location, and `pos` is always set to `0`.","code":"fn roll(&mut self) {\n if self.pos == self.end {\n self.pos = 0;\n self.last_lineterm = 0;\n self.end = 0;\n return;\n }\n\n let roll_len = self.end - self.pos;\n self.buf.copy_within(self.pos..self.end, 0);\n self.pos = 0;\n self.last_lineterm = roll_len;\n self.end = roll_len;\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":499,"symbol":"ensure_capacity","kind":"function","lang":"rust","doc":"Ensures that the internal buffer has a non-zero amount of free space in which to read more data. If there is no free space, then more is allocated. If the allocation must exceed the configured limit, then this returns an error.","code":"fn ensure_capacity(&mut self) -> Result<(), io::Error> {\n if !self.free_buffer().is_empty() {\n return Ok(());\n }\n // `len` is used for computing the next allocation size. The capacity\n // is permitted to start at `0`, so we make sure it's at least `1`.\n let len = std::cmp::max(1, self.buf.len());\n let additional = match self.config.buffer_alloc {\n BufferAllocation::Eager => len * 2,\n BufferAllocation::Error(limit) => {\n let used = self.buf.len() - self.config.capacity;\n let n = std::cmp::min(len * 2, limit - used);\n if n == 0 {\n return Err(alloc_error(self.config.capacity + limit));\n }\n n\n }\n };\n assert!(additional > 0);\n let newlen = self.buf.len() + additional;\n self.buf.resize(newlen, 0);\n assert!(!self.free_buffer().is_empty());\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":527,"symbol":"replace_bytes","kind":"function","lang":"rust","doc":"Replaces `src` with `replacement` in bytes, and return the offset of the first replacement, if one exists.","code":"fn replace_bytes(\n mut bytes: &mut [u8],\n src: u8,\n replacement: u8,\n) -> Option {\n if src == replacement {\n return None;\n }\n let first_pos = bytes.find_byte(src)?;\n bytes[first_pos] = replacement;\n bytes = &mut bytes[first_pos + 1..];\n while let Some(i) = bytes.find_byte(src) {\n bytes[i] = replacement;\n bytes = &mut bytes[i + 1..];\n\n // To search for adjacent `src` bytes we use a different strategy.\n // Since binary data tends to have long runs of NUL terminators,\n // it is faster to compare one-byte-at-a-time than to stop and start\n // memchr (through `find_byte`) for every byte in a sequence.\n while bytes.get(0) == Some(&src) {\n bytes[0] = replacement;\n bytes = &mut bytes[1..];\n }\n }\n Some(first_pos)\n}"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":569,"symbol":"s","kind":"function","lang":"rust","code":"fn s(slice: &str) -> String {\n slice.to_string()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":573,"symbol":"replace_str","kind":"function","lang":"rust","code":"fn replace_str(\n slice: &str,\n src: u8,\n replacement: u8,\n ) -> (String, Option) {\n let mut dst = Vec::from(slice);\n let result = replace_bytes(&mut dst, src, replacement);\n (dst.into_string().unwrap(), result)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":584,"symbol":"replace","kind":"function","lang":"rust","code":"fn replace() {\n assert_eq!(replace_str(\"\", b'b', b'z'), (s(\"\"), None));\n assert_eq!(replace_str(\"a\", b'a', b'a'), (s(\"a\"), None));\n assert_eq!(replace_str(\"a\", b'b', b'z'), (s(\"a\"), None));\n assert_eq!(replace_str(\"abc\", b'b', b'z'), (s(\"azc\"), Some(1)));\n assert_eq!(replace_str(\"abb\", b'b', b'z'), (s(\"azz\"), Some(1)));\n assert_eq!(replace_str(\"aba\", b'a', b'z'), (s(\"zbz\"), Some(0)));\n assert_eq!(replace_str(\"bbb\", b'b', b'z'), (s(\"zzz\"), Some(0)));\n assert_eq!(replace_str(\"bac\", b'b', b'z'), (s(\"zac\"), Some(0)));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":596,"symbol":"buffer_basics1","kind":"function","lang":"rust","code":"fn buffer_basics1() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\n\");\n assert_eq!(rdr.absolute_byte_offset(), 0);\n rdr.consume(5);\n assert_eq!(rdr.absolute_byte_offset(), 5);\n rdr.consume_all();\n assert_eq!(rdr.absolute_byte_offset(), 11);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"maggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":621,"symbol":"buffer_basics2","kind":"function","lang":"rust","code":"fn buffer_basics2() {\n let bytes = \"homer\\nlisa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":636,"symbol":"buffer_basics3","kind":"function","lang":"rust","code":"fn buffer_basics3() {\n let bytes = \"\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":651,"symbol":"buffer_basics4","kind":"function","lang":"rust","code":"fn buffer_basics4() {\n let bytes = \"\\n\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\\n\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":666,"symbol":"buffer_empty","kind":"function","lang":"rust","code":"fn buffer_empty() {\n let bytes = \"\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":677,"symbol":"buffer_zero_capacity","kind":"function","lang":"rust","code":"fn buffer_zero_capacity() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new().capacity(0).build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n while rdr.fill().unwrap() {\n rdr.consume_all();\n }\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":690,"symbol":"buffer_small_capacity","kind":"function","lang":"rust","code":"fn buffer_small_capacity() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new().capacity(1).build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n let mut got = vec![];\n while rdr.fill().unwrap() {\n got.push_str(rdr.buffer());\n rdr.consume_all();\n }\n assert_eq!(bytes, got.as_bstr());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":706,"symbol":"buffer_limited_capacity1","kind":"function","lang":"rust","code":"fn buffer_limited_capacity1() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new()\n .capacity(1)\n .buffer_alloc(BufferAllocation::Error(5))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\n\");\n rdr.consume_all();\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"lisa\\n\");\n rdr.consume_all();\n\n // This returns an error because while we have just enough room to\n // store maggie in the buffer, we *don't* have enough room to read one\n // more byte, so we don't know whether we're at EOF or not, and\n // therefore must give up.\n assert!(rdr.fill().is_err());\n\n // We can mush on though!\n assert_eq!(rdr.bstr(), \"m\");\n rdr.consume_all();\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"aggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":740,"symbol":"buffer_limited_capacity2","kind":"function","lang":"rust","code":"fn buffer_limited_capacity2() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new()\n .capacity(1)\n .buffer_alloc(BufferAllocation::Error(6))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\n\");\n rdr.consume_all();\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"lisa\\n\");\n rdr.consume_all();\n\n // We have just enough space.\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"maggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":765,"symbol":"buffer_limited_capacity3","kind":"function","lang":"rust","code":"fn buffer_limited_capacity3() {\n let bytes = \"homer\\nlisa\\nmaggie\";\n let mut linebuf = LineBufferBuilder::new()\n .capacity(1)\n .buffer_alloc(BufferAllocation::Error(0))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.fill().is_err());\n assert_eq!(rdr.bstr(), \"\");\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":778,"symbol":"buffer_binary_none","kind":"function","lang":"rust","code":"fn buffer_binary_none() {\n let bytes = \"homer\\nli\\x00sa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new().build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nli\\x00sa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":795,"symbol":"buffer_binary_quit1","kind":"function","lang":"rust","code":"fn buffer_binary_quit1() {\n let bytes = \"homer\\nli\\x00sa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nli\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), 8);\n assert_eq!(rdr.binary_byte_offset(), Some(8));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":814,"symbol":"buffer_binary_quit2","kind":"function","lang":"rust","code":"fn buffer_binary_quit2() {\n let bytes = \"\\x00homer\\nlisa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\");\n assert_eq!(rdr.absolute_byte_offset(), 0);\n assert_eq!(rdr.binary_byte_offset(), Some(0));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":828,"symbol":"buffer_binary_quit3","kind":"function","lang":"rust","code":"fn buffer_binary_quit3() {\n let bytes = \"homer\\nlisa\\nmaggie\\n\\x00\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64 - 1);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 1));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":847,"symbol":"buffer_binary_quit4","kind":"function","lang":"rust","code":"fn buffer_binary_quit4() {\n let bytes = \"homer\\nlisa\\nmaggie\\x00\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64 - 2);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 2));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":866,"symbol":"buffer_binary_quit5","kind":"function","lang":"rust","code":"fn buffer_binary_quit5() {\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Quit(b'u'))\n .build();\n let mut rdr = LineBufferReader::new(SHERLOCK.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(\n rdr.bstr(),\n \"\\\nFor the Doctor Watsons of this world, as opposed to the Sherlock\nHolmeses, s\\\n\"\n );\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), 76);\n assert_eq!(rdr.binary_byte_offset(), Some(76));\n assert_eq!(SHERLOCK.as_bytes()[76], b'u');\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":891,"symbol":"buffer_binary_convert1","kind":"function","lang":"rust","code":"fn buffer_binary_convert1() {\n let bytes = \"homer\\nli\\x00sa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nli\\nsa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(8));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":910,"symbol":"buffer_binary_convert2","kind":"function","lang":"rust","code":"fn buffer_binary_convert2() {\n let bytes = \"\\x00homer\\nlisa\\nmaggie\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"\\nhomer\\nlisa\\nmaggie\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(0));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":929,"symbol":"buffer_binary_convert3","kind":"function","lang":"rust","code":"fn buffer_binary_convert3() {\n let bytes = \"homer\\nlisa\\nmaggie\\n\\x00\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 1));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/line_buffer.rs","line":948,"symbol":"buffer_binary_convert4","kind":"function","lang":"rust","code":"fn buffer_binary_convert4() {\n let bytes = \"homer\\nlisa\\nmaggie\\x00\\n\";\n let mut linebuf = LineBufferBuilder::new()\n .binary_detection(BinaryDetection::Convert(b'\\x00'))\n .build();\n let mut rdr = LineBufferReader::new(bytes.as_bytes(), &mut linebuf);\n\n assert!(rdr.buffer().is_empty());\n\n assert!(rdr.fill().unwrap());\n assert_eq!(rdr.bstr(), \"homer\\nlisa\\nmaggie\\n\\n\");\n rdr.consume_all();\n\n assert!(!rdr.fill().unwrap());\n assert_eq!(rdr.absolute_byte_offset(), bytes.len() as u64);\n assert_eq!(rdr.binary_byte_offset(), Some(bytes.len() as u64 - 2));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":17,"symbol":"LineIter","kind":"type","lang":"rust","doc":"An iterator over lines in a particular slice of bytes. Line terminators are considered part of the line they terminate. All lines yielded by the iterator are guaranteed to be non-empty. `'b` refers to the lifetime of the underlying bytes.","code":"pub struct LineIter<'b> {\n bytes: &'b [u8],\n stepper: LineStep,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":25,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new line iterator that yields lines in the given bytes that are terminated by `line_term`.","code":"pub fn new(line_term: u8, bytes: &'b [u8]) -> LineIter<'b> {\n let stepper = LineStep::new(line_term, 0, bytes.len());\n LineIter { bytes, stepper }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":34,"symbol":"next","kind":"function","lang":"rust","code":"fn next(&mut self) -> Option<&'b [u8]> {\n self.stepper.next_match(self.bytes).map(|m| &self.bytes[m])\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":49,"symbol":"LineStep","kind":"type","lang":"rust","doc":"callers to explicitly provide the bytes when moving through the iterator. While not idiomatic, this provides a simple way of iterating over lines that doesn't require borrowing the slice itself, which can be convenient. Line terminators are considered part of the line they terminate. All lines yielded by the iterator are guaranteed to be non-empty.","code":"pub struct LineStep {\n line_term: u8,\n pos: usize,\n end: usize,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":63,"symbol":"new","kind":"function","lang":"rust","doc":"given line terminator. Callers should provide the actual bytes for each call to `next`. The same slice must be provided to each call. This panics if `start` is not less than or equal to `end`.","code":"pub fn new(line_term: u8, start: usize, end: usize) -> LineStep {\n LineStep { line_term, pos: start, end }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":74,"symbol":"next","kind":"function","lang":"rust","doc":"The caller must past exactly the same slice of bytes for each call to `next`. The range returned includes the line terminator. Ranges are always non-empty.","code":"pub fn next(&mut self, bytes: &[u8]) -> Option<(usize, usize)> {\n self.next_impl(bytes)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":80,"symbol":"next_match","kind":"function","lang":"rust","doc":"Like next, but returns a `Match` instead of a tuple.","code":"pub(crate) fn next_match(&mut self, bytes: &[u8]) -> Option {\n self.next_impl(bytes).map(|(s, e)| Match::new(s, e))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":85,"symbol":"next_impl","kind":"function","lang":"rust","code":"fn next_impl(&mut self, mut bytes: &[u8]) -> Option<(usize, usize)> {\n bytes = &bytes[..self.end];\n match bytes[self.pos..].find_byte(self.line_term) {\n None => {\n if self.pos < bytes.len() {\n let m = (self.pos, bytes.len());\n assert!(m.0 <= m.1);\n\n self.pos = m.1;\n Some(m)\n } else {\n None\n }\n }\n Some(line_end) => {\n let m = (self.pos, self.pos + line_end + 1);\n assert!(m.0 <= m.1);\n\n self.pos = m.1;\n Some(m)\n }\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":111,"symbol":"count","kind":"function","lang":"rust","doc":"Count the number of occurrences of `line_term` in `bytes`.","code":"pub(crate) fn count(bytes: &[u8], line_term: u8) -> u64 {\n memchr::memchr_iter(line_term, bytes).count() as u64\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":118,"symbol":"without_terminator","kind":"function","lang":"rust","doc":"Given a line that possibly ends with a terminator, return that line without the terminator.","code":"pub(crate) fn without_terminator(\n bytes: &[u8],\n line_term: LineTerminator,\n) -> &[u8] {\n let line_term = line_term.as_bytes();\n let start = bytes.len().saturating_sub(line_term.len());\n if bytes.get(start..) == Some(line_term) {\n return &bytes[..bytes.len() - line_term.len()];\n }\n bytes\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":135,"symbol":"locate","kind":"function","lang":"rust","doc":"Return the start and end offsets of the lines containing the given range of bytes. Line terminators are considered part of the line they terminate.","code":"pub(crate) fn locate(bytes: &[u8], line_term: u8, range: Match) -> Match {\n let line_start =\n bytes[..range.start()].rfind_byte(line_term).map_or(0, |i| i + 1);\n let line_end =\n if range.end() > line_start && bytes[range.end() - 1] == line_term {\n range.end()\n } else {\n bytes[range.end()..]\n .find_byte(line_term)\n .map_or(bytes.len(), |i| range.end() + i + 1)\n };\n Match::new(line_start, line_end)\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":157,"symbol":"preceding","kind":"function","lang":"rust","doc":"Lines are terminated by `line_term`. If `count` is zero, then this returns the starting offset of the last line in `bytes`. If `bytes` ends with a line terminator, then the terminator itself is considered part of the last line.","code":"pub(crate) fn preceding(bytes: &[u8], line_term: u8, count: usize) -> usize {\n preceding_by_pos(bytes, bytes.len(), line_term, count)\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":170,"symbol":"preceding_by_pos","kind":"function","lang":"rust","doc":"containing `pos`. If `pos` points just past a line terminator, then it is considered part of the line that it terminates. For example, given `bytes = b\"abc\\nxyz\\n\"` and `pos = 7`, `preceding(bytes, pos, b'\\n', 0)` returns `4` (as does `pos = 8`) and `preceding(bytes, pos, `b'\\n', 1)` returns `0`.","code":"fn preceding_by_pos(\n bytes: &[u8],\n mut pos: usize,\n line_term: u8,\n mut count: usize,\n) -> usize {\n if pos == 0 {\n return 0;\n } else if bytes[pos - 1] == line_term {\n pos -= 1;\n }\n loop {\n match bytes[..pos].rfind_byte(line_term) {\n None => {\n return 0;\n }\n Some(i) => {\n if count == 0 {\n return i + 1;\n } else if i == 0 {\n return 0;\n }\n count -= 1;\n pos = i;\n }\n }\n }\n}"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":212,"symbol":"m","kind":"function","lang":"rust","code":"fn m(start: usize, end: usize) -> Match {\n Match::new(start, end)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":216,"symbol":"lines","kind":"function","lang":"rust","code":"fn lines(text: &str) -> Vec<&str> {\n let mut results = vec![];\n let mut it = LineStep::new(b'\\n', 0, text.len());\n while let Some(m) = it.next_match(text.as_bytes()) {\n results.push(&text[m]);\n }\n results\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":225,"symbol":"line_ranges","kind":"function","lang":"rust","code":"fn line_ranges(text: &str) -> Vec> {\n let mut results = vec![];\n let mut it = LineStep::new(b'\\n', 0, text.len());\n while let Some(m) = it.next_match(text.as_bytes()) {\n results.push(m.start()..m.end());\n }\n results\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":234,"symbol":"prev","kind":"function","lang":"rust","code":"fn prev(text: &str, pos: usize, count: usize) -> usize {\n preceding_by_pos(text.as_bytes(), pos, b'\\n', count)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":238,"symbol":"loc","kind":"function","lang":"rust","code":"fn loc(text: &str, start: usize, end: usize) -> Match {\n locate(text.as_bytes(), b'\\n', Match::new(start, end))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":243,"symbol":"line_count","kind":"function","lang":"rust","code":"fn line_count() {\n assert_eq!(0, count(b\"\", b'\\n'));\n assert_eq!(1, count(b\"\\n\", b'\\n'));\n assert_eq!(2, count(b\"\\n\\n\", b'\\n'));\n assert_eq!(2, count(b\"a\\nb\\nc\", b'\\n'));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":251,"symbol":"line_locate","kind":"function","lang":"rust","code":"fn line_locate() {\n let t = SHERLOCK;\n let lines = line_ranges(t);\n\n assert_eq!(\n loc(t, lines[0].start, lines[0].end),\n m(lines[0].start, lines[0].end)\n );\n assert_eq!(\n loc(t, lines[0].start + 1, lines[0].end),\n m(lines[0].start, lines[0].end)\n );\n assert_eq!(\n loc(t, lines[0].end - 1, lines[0].end),\n m(lines[0].start, lines[0].end)\n );\n assert_eq!(\n loc(t, lines[0].end, lines[0].end),\n m(lines[1].start, lines[1].end)\n );\n\n assert_eq!(\n loc(t, lines[5].start, lines[5].end),\n m(lines[5].start, lines[5].end)\n );\n assert_eq!(\n loc(t, lines[5].start + 1, lines[5].end),\n m(lines[5].start, lines[5].end)\n );\n assert_eq!(\n loc(t, lines[5].end - 1, lines[5].end),\n m(lines[5].start, lines[5].end)\n );\n assert_eq!(\n loc(t, lines[5].end, lines[5].end),\n m(lines[5].start, lines[5].end)\n );\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":291,"symbol":"line_locate_weird","kind":"function","lang":"rust","code":"fn line_locate_weird() {\n assert_eq!(loc(\"\", 0, 0), m(0, 0));\n\n assert_eq!(loc(\"\\n\", 0, 1), m(0, 1));\n assert_eq!(loc(\"\\n\", 1, 1), m(1, 1));\n\n assert_eq!(loc(\"\\n\\n\", 0, 0), m(0, 1));\n assert_eq!(loc(\"\\n\\n\", 0, 1), m(0, 1));\n assert_eq!(loc(\"\\n\\n\", 1, 1), m(1, 2));\n assert_eq!(loc(\"\\n\\n\", 1, 2), m(1, 2));\n assert_eq!(loc(\"\\n\\n\", 2, 2), m(2, 2));\n\n assert_eq!(loc(\"a\\nb\\nc\", 0, 1), m(0, 2));\n assert_eq!(loc(\"a\\nb\\nc\", 1, 2), m(0, 2));\n assert_eq!(loc(\"a\\nb\\nc\", 2, 3), m(2, 4));\n assert_eq!(loc(\"a\\nb\\nc\", 3, 4), m(2, 4));\n assert_eq!(loc(\"a\\nb\\nc\", 4, 5), m(4, 5));\n assert_eq!(loc(\"a\\nb\\nc\", 5, 5), m(4, 5));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":312,"symbol":"line_iter","kind":"function","lang":"rust","code":"fn line_iter() {\n assert_eq!(lines(\"abc\"), vec![\"abc\"]);\n\n assert_eq!(lines(\"abc\\n\"), vec![\"abc\\n\"]);\n assert_eq!(lines(\"abc\\nxyz\"), vec![\"abc\\n\", \"xyz\"]);\n assert_eq!(lines(\"abc\\nxyz\\n\"), vec![\"abc\\n\", \"xyz\\n\"]);\n\n assert_eq!(lines(\"abc\\n\\n\"), vec![\"abc\\n\", \"\\n\"]);\n assert_eq!(lines(\"abc\\n\\n\\n\"), vec![\"abc\\n\", \"\\n\", \"\\n\"]);\n assert_eq!(lines(\"abc\\n\\nxyz\"), vec![\"abc\\n\", \"\\n\", \"xyz\"]);\n assert_eq!(lines(\"abc\\n\\nxyz\\n\"), vec![\"abc\\n\", \"\\n\", \"xyz\\n\"]);\n assert_eq!(lines(\"abc\\nxyz\\n\\n\"), vec![\"abc\\n\", \"xyz\\n\", \"\\n\"]);\n\n assert_eq!(lines(\"\\n\"), vec![\"\\n\"]);\n assert_eq!(lines(\"\"), Vec::<&str>::new());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":330,"symbol":"line_iter_empty","kind":"function","lang":"rust","code":"fn line_iter_empty() {\n let mut it = LineStep::new(b'\\n', 0, 0);\n assert_eq!(it.next(b\"abc\"), None);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":336,"symbol":"preceding_lines_doc","kind":"function","lang":"rust","code":"fn preceding_lines_doc() {\n // These are the examples mentions in the documentation of `preceding`.\n let bytes = b\"abc\\nxyz\\n\";\n assert_eq!(4, preceding_by_pos(bytes, 7, b'\\n', 0));\n assert_eq!(4, preceding_by_pos(bytes, 8, b'\\n', 0));\n assert_eq!(0, preceding_by_pos(bytes, 7, b'\\n', 1));\n assert_eq!(0, preceding_by_pos(bytes, 8, b'\\n', 1));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":346,"symbol":"preceding_lines_sherlock","kind":"function","lang":"rust","code":"fn preceding_lines_sherlock() {\n let t = SHERLOCK;\n let lines = line_ranges(t);\n\n // The following tests check the count == 0 case, i.e., finding the\n // beginning of the line containing the given position.\n assert_eq!(0, prev(t, 0, 0));\n assert_eq!(0, prev(t, 1, 0));\n // The line terminator is addressed by `end-1` and terminates the line\n // it is part of.\n assert_eq!(0, prev(t, lines[0].end - 1, 0));\n assert_eq!(lines[0].start, prev(t, lines[0].end, 0));\n // The end position of line addresses the byte immediately following a\n // line terminator, which puts it on the following line.\n assert_eq!(lines[1].start, prev(t, lines[0].end + 1, 0));\n\n // Now tests for count > 0.\n assert_eq!(0, prev(t, 0, 1));\n assert_eq!(0, prev(t, 0, 2));\n assert_eq!(0, prev(t, 1, 1));\n assert_eq!(0, prev(t, 1, 2));\n assert_eq!(0, prev(t, lines[0].end - 1, 1));\n assert_eq!(0, prev(t, lines[0].end - 1, 2));\n assert_eq!(0, prev(t, lines[0].end, 1));\n assert_eq!(0, prev(t, lines[0].end, 2));\n assert_eq!(lines[3].start, prev(t, lines[4].end - 1, 1));\n"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":383,"symbol":"preceding_lines_short","kind":"function","lang":"rust","code":"fn preceding_lines_short() {\n let t = \"a\\nb\\nc\\nd\\ne\\nf\\n\";\n let lines = line_ranges(t);\n assert_eq!(12, t.len());\n\n assert_eq!(lines[5].start, prev(t, lines[5].end, 0));\n assert_eq!(lines[4].start, prev(t, lines[5].end, 1));\n assert_eq!(lines[3].start, prev(t, lines[5].end, 2));\n assert_eq!(lines[2].start, prev(t, lines[5].end, 3));\n assert_eq!(lines[1].start, prev(t, lines[5].end, 4));\n assert_eq!(lines[0].start, prev(t, lines[5].end, 5));\n assert_eq!(lines[0].start, prev(t, lines[5].end, 6));\n\n assert_eq!(lines[5].start, prev(t, lines[5].end - 1, 0));\n assert_eq!(lines[4].start, prev(t, lines[5].end - 1, 1));\n assert_eq!(lines[3].start, prev(t, lines[5].end - 1, 2));\n assert_eq!(lines[2].start, prev(t, lines[5].end - 1, 3));\n assert_eq!(lines[1].start, prev(t, lines[5].end - 1, 4));\n assert_eq!(lines[0].start, prev(t, lines[5].end - 1, 5));\n assert_eq!(lines[0].start, prev(t, lines[5].end - 1, 6));\n\n assert_eq!(lines[4].start, prev(t, lines[5].start, 0));\n assert_eq!(lines[3].start, prev(t, lines[5].start, 1));\n assert_eq!(lines[2].start, pr"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":428,"symbol":"preceding_lines_empty1","kind":"function","lang":"rust","code":"fn preceding_lines_empty1() {\n let t = \"\\n\\n\\nd\\ne\\nf\\n\";\n let lines = line_ranges(t);\n assert_eq!(9, t.len());\n\n assert_eq!(lines[0].start, prev(t, lines[0].end, 0));\n assert_eq!(lines[0].start, prev(t, lines[0].end, 1));\n assert_eq!(lines[1].start, prev(t, lines[1].end, 0));\n assert_eq!(lines[0].start, prev(t, lines[1].end, 1));\n\n assert_eq!(lines[5].start, prev(t, lines[5].end, 0));\n assert_eq!(lines[4].start, prev(t, lines[5].end, 1));\n assert_eq!(lines[3].start, prev(t, lines[5].end, 2));\n assert_eq!(lines[2].start, prev(t, lines[5].end, 3));\n assert_eq!(lines[1].start, prev(t, lines[5].end, 4));\n assert_eq!(lines[0].start, prev(t, lines[5].end, 5));\n assert_eq!(lines[0].start, prev(t, lines[5].end, 6));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/lines.rs","line":448,"symbol":"preceding_lines_empty2","kind":"function","lang":"rust","code":"fn preceding_lines_empty2() {\n let t = \"a\\n\\n\\nd\\ne\\nf\\n\";\n let lines = line_ranges(t);\n assert_eq!(10, t.len());\n\n assert_eq!(lines[0].start, prev(t, lines[0].end, 0));\n assert_eq!(lines[0].start, prev(t, lines[0].end, 1));\n assert_eq!(lines[1].start, prev(t, lines[1].end, 0));\n assert_eq!(lines[0].start, prev(t, lines[1].end, 1));\n\n assert_eq!(lines[5].start, prev(t, lines[5].end, 0));\n assert_eq!(lines[4].start, prev(t, lines[5].end, 1));\n assert_eq!(lines[3].start, prev(t, lines[5].end, 2));\n assert_eq!(lines[2].start, prev(t, lines[5].end, 3));\n assert_eq!(lines[1].start, prev(t, lines[5].end, 4));\n assert_eq!(lines[0].start, prev(t, lines[5].end, 5));\n assert_eq!(lines[0].start, prev(t, lines[5].end, 6));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":14,"symbol":"FastMatchResult","kind":"type","lang":"rust","code":"enum FastMatchResult {\n Continue,\n Stop,\n SwitchToSlow,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":21,"symbol":"Core","kind":"type","lang":"rust","code":"pub(crate) struct Core<'s, M: 's, S> {\n config: &'s Config,\n matcher: M,\n searcher: &'s Searcher,\n sink: S,\n binary: bool,\n pos: usize,\n absolute_byte_offset: u64,\n binary_byte_offset: Option,\n line_number: Option,\n last_line_counted: usize,\n last_line_visited: usize,\n after_context_left: usize,\n has_sunk: bool,\n has_matched: bool,\n count: u64,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":40,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(\n searcher: &'s Searcher,\n matcher: M,\n sink: S,\n binary: bool,\n ) -> Core<'s, M, S> {\n let line_number =\n if searcher.config.line_number { Some(1) } else { None };\n let core = Core {\n config: &searcher.config,\n matcher,\n searcher,\n sink,\n binary,\n pos: 0,\n absolute_byte_offset: 0,\n binary_byte_offset: None,\n line_number,\n last_line_counted: 0,\n last_line_visited: 0,\n after_context_left: 0,\n has_sunk: false,\n has_matched: false,\n count: 0,\n };\n if !core.searcher.multi_line_with_matcher(&core.matcher) {\n if core.is_line_by_line_fast() {\n log::trace!(\"searcher core: will use fast line searcher\");\n } else {\n log::trace!(\"searcher core: will use slow line searcher\");\n }\n }\n core\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":75,"symbol":"pos","kind":"function","lang":"rust","code":"pub(crate) fn pos(&self) -> usize {\n self.pos\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":79,"symbol":"set_pos","kind":"function","lang":"rust","code":"pub(crate) fn set_pos(&mut self, pos: usize) {\n self.pos = pos;\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":83,"symbol":"count","kind":"function","lang":"rust","code":"fn count(&self) -> u64 {\n self.count\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":87,"symbol":"increment_count","kind":"function","lang":"rust","code":"fn increment_count(&mut self) {\n self.count += 1;\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":91,"symbol":"binary_byte_offset","kind":"function","lang":"rust","code":"pub(crate) fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset.map(|offset| offset as u64)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":95,"symbol":"matcher","kind":"function","lang":"rust","code":"pub(crate) fn matcher(&self) -> &M {\n &self.matcher\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":99,"symbol":"matched","kind":"function","lang":"rust","code":"pub(crate) fn matched(\n &mut self,\n buf: &[u8],\n range: &Range,\n ) -> Result {\n self.sink_matched(buf, range)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":107,"symbol":"binary_data","kind":"function","lang":"rust","code":"pub(crate) fn binary_data(\n &mut self,\n binary_byte_offset: u64,\n ) -> Result {\n self.sink.binary_data(&self.searcher, binary_byte_offset)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":114,"symbol":"is_match","kind":"function","lang":"rust","code":"fn is_match(&self, line: &[u8]) -> Result {\n // We need to strip the line terminator here to match the\n // semantics of line-by-line searching. Namely, regexes\n // like `(?m)^$` can match at the final position beyond a\n // line terminator, which is non-sensical in line oriented\n // matching.\n let line = lines::without_terminator(line, self.config.line_term);\n self.matcher.is_match(line).map_err(S::Error::error_message)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":124,"symbol":"find","kind":"function","lang":"rust","code":"pub(crate) fn find(\n &mut self,\n slice: &[u8],\n ) -> Result, S::Error> {\n if self.has_exceeded_match_limit() {\n return Ok(None);\n }\n match self.matcher().find(slice) {\n Err(err) => Err(S::Error::error_message(err)),\n Ok(None) => Ok(None),\n Ok(Some(m)) => {\n self.increment_count();\n Ok(Some(m))\n }\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":141,"symbol":"shortest_match","kind":"function","lang":"rust","code":"fn shortest_match(\n &mut self,\n slice: &[u8],\n ) -> Result, S::Error> {\n if self.has_exceeded_match_limit() {\n return Ok(None);\n }\n match self.matcher.shortest_match(slice) {\n Err(err) => return Err(S::Error::error_message(err)),\n Ok(None) => return Ok(None),\n Ok(Some(m)) => Ok(Some(m)),\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":155,"symbol":"begin","kind":"function","lang":"rust","code":"pub(crate) fn begin(&mut self) -> Result {\n self.sink.begin(&self.searcher)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":159,"symbol":"finish","kind":"function","lang":"rust","code":"pub(crate) fn finish(\n &mut self,\n byte_count: u64,\n binary_byte_offset: Option,\n ) -> Result<(), S::Error> {\n self.sink.finish(\n &self.searcher,\n &SinkFinish { byte_count, binary_byte_offset },\n )\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":170,"symbol":"match_by_line","kind":"function","lang":"rust","code":"pub(crate) fn match_by_line(\n &mut self,\n buf: &[u8],\n ) -> Result {\n if self.is_line_by_line_fast() {\n match self.match_by_line_fast(buf)? {\n FastMatchResult::SwitchToSlow => self.match_by_line_slow(buf),\n FastMatchResult::Continue => Ok(true),\n FastMatchResult::Stop => Ok(false),\n }\n } else {\n self.match_by_line_slow(buf)\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":185,"symbol":"roll","kind":"function","lang":"rust","code":"pub(crate) fn roll(&mut self, buf: &[u8]) -> usize {\n let consumed = if self.config.max_context() == 0 {\n buf.len()\n } else {\n // It might seem like all we need to care about here is just\n // the \"before context,\" but in order to sink the context\n // separator (when before_context==0 and after_context>0), we\n // need to know something about the position of the previous\n // line visited, even if we're at the beginning of the buffer.\n //\n // ... however, we only need to find the N preceding lines based\n // on before context. We can skip this (potentially costly, for\n // large values of N) step when before_context==0.\n let context_start = lines::preceding(\n buf,\n self.config.line_term.as_byte(),\n self.config.before_context,\n );\n let consumed =\n std::cmp::max(context_start, self.last_line_visited);\n consumed\n };\n self.count_lines(buf, consumed);\n self.absolute_byte_offset += consumed as u64;\n self.last_line_counted = 0;\n self.l"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":215,"symbol":"detect_binary","kind":"function","lang":"rust","code":"pub(crate) fn detect_binary(\n &mut self,\n buf: &[u8],\n range: &Range,\n ) -> Result {\n if self.binary_byte_offset.is_some() {\n return Ok(self.config.binary.quit_byte().is_some());\n }\n let binary_byte = match self.config.binary.0 {\n BinaryDetection::Quit(b) => b,\n BinaryDetection::Convert(b) => b,\n _ => return Ok(false),\n };\n if let Some(i) = buf[*range].find_byte(binary_byte) {\n let offset = range.start() + i;\n self.binary_byte_offset = Some(offset);\n if !self.binary_data(offset as u64)? {\n return Ok(true);\n }\n Ok(self.config.binary.quit_byte().is_some())\n } else {\n Ok(false)\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":240,"symbol":"before_context_by_line","kind":"function","lang":"rust","code":"pub(crate) fn before_context_by_line(\n &mut self,\n buf: &[u8],\n upto: usize,\n ) -> Result {\n if self.config.before_context == 0 {\n return Ok(true);\n }\n let range = Range::new(self.last_line_visited, upto);\n if range.is_empty() {\n return Ok(true);\n }\n let before_context_start = range.start()\n + lines::preceding(\n &buf[range],\n self.config.line_term.as_byte(),\n self.config.before_context - 1,\n );\n\n let range = Range::new(before_context_start, range.end());\n let mut stepper = LineStep::new(\n self.config.line_term.as_byte(),\n range.start(),\n range.end(),\n );\n while let Some(line) = stepper.next_match(buf) {\n if !self.sink_break_context(line.start())? {\n return Ok(false);\n }\n if !self.sink_before_context(buf, &line)? {\n return Ok(false);\n }\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":276,"symbol":"after_context_by_line","kind":"function","lang":"rust","code":"pub(crate) fn after_context_by_line(\n &mut self,\n buf: &[u8],\n upto: usize,\n ) -> Result {\n if self.after_context_left == 0 {\n return Ok(true);\n }\n let exceeded_match_limit = self.has_exceeded_match_limit();\n let range = Range::new(self.last_line_visited, upto);\n let mut stepper = LineStep::new(\n self.config.line_term.as_byte(),\n range.start(),\n range.end(),\n );\n while let Some(line) = stepper.next_match(buf) {\n if exceeded_match_limit\n && self.is_match(&buf[line])? != self.config.invert_match\n {\n let after_context_left = self.after_context_left;\n self.set_pos(line.end());\n if !self.sink_matched(buf, &line)? {\n return Ok(false);\n }\n self.after_context_left = after_context_left - 1;\n } else if !self.sink_after_context(buf, &line)? {\n return Ok(false);\n }\n if self.after_context_left == 0 {\n break;\n }\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":311,"symbol":"other_context_by_line","kind":"function","lang":"rust","code":"pub(crate) fn other_context_by_line(\n &mut self,\n buf: &[u8],\n upto: usize,\n ) -> Result {\n let range = Range::new(self.last_line_visited, upto);\n let mut stepper = LineStep::new(\n self.config.line_term.as_byte(),\n range.start(),\n range.end(),\n );\n while let Some(line) = stepper.next_match(buf) {\n if !self.sink_other_context(buf, &line)? {\n return Ok(false);\n }\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":330,"symbol":"match_by_line_slow","kind":"function","lang":"rust","code":"fn match_by_line_slow(&mut self, buf: &[u8]) -> Result {\n debug_assert!(!self.searcher.multi_line_with_matcher(&self.matcher));\n\n let range = Range::new(self.pos(), buf.len());\n let mut stepper = LineStep::new(\n self.config.line_term.as_byte(),\n range.start(),\n range.end(),\n );\n while let Some(line) = stepper.next_match(buf) {\n if self.has_exceeded_match_limit()\n && !self.config.passthru\n && self.after_context_left == 0\n {\n return Ok(false);\n }\n let matched = {\n // Stripping the line terminator is necessary to prevent some\n // classes of regexes from matching the empty position *after*\n // the end of the line. For example, `(?m)^$` will match at\n // position (2, 2) in the string `a\\n`.\n let slice = lines::without_terminator(\n &buf[line],\n self.config.line_term,\n );\n self.shortest_match(slice)?.is_some()\n };\n self.set_pos(line.end());\n\n let"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":385,"symbol":"match_by_line_fast","kind":"function","lang":"rust","code":"fn match_by_line_fast(\n &mut self,\n buf: &[u8],\n ) -> Result {\n use FastMatchResult::*;\n\n debug_assert!(!self.config.passthru);\n while !buf[self.pos()..].is_empty() {\n if self.config.stop_on_nonmatch && self.has_matched {\n return Ok(SwitchToSlow);\n }\n if self.config.invert_match {\n if !self.match_by_line_fast_invert(buf)? {\n break;\n }\n } else if let Some(line) = self.find_by_line_fast(buf)? {\n self.has_matched = true;\n self.increment_count();\n if self.config.max_context() > 0 {\n if !self.after_context_by_line(buf, line.start())? {\n return Ok(Stop);\n }\n if !self.before_context_by_line(buf, line.start())? {\n return Ok(Stop);\n }\n }\n self.set_pos(line.end());\n if !self.sink_matched(buf, &line)? {\n return Ok(Stop);\n }\n } else {\n break;\n }\n"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":430,"symbol":"match_by_line_fast_invert","kind":"function","lang":"rust","code":"fn match_by_line_fast_invert(\n &mut self,\n buf: &[u8],\n ) -> Result {\n assert!(self.config.invert_match);\n\n let invert_match = match self.find_by_line_fast(buf)? {\n None => {\n let range = Range::new(self.pos(), buf.len());\n self.set_pos(range.end());\n range\n }\n Some(line) => {\n let range = Range::new(self.pos(), line.start());\n self.set_pos(line.end());\n range\n }\n };\n if invert_match.is_empty() {\n return Ok(true);\n }\n self.has_matched = true;\n if !self.after_context_by_line(buf, invert_match.start())? {\n return Ok(false);\n }\n if !self.before_context_by_line(buf, invert_match.start())? {\n return Ok(false);\n }\n let mut stepper = LineStep::new(\n self.config.line_term.as_byte(),\n invert_match.start(),\n invert_match.end(),\n );\n while let Some(line) = stepper.next_match(buf) {\n self.increment_count();\n if !self.sink_matched(buf, &line)? {\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":476,"symbol":"find_by_line_fast","kind":"function","lang":"rust","code":"fn find_by_line_fast(\n &mut self,\n buf: &[u8],\n ) -> Result, S::Error> {\n debug_assert!(!self.searcher.multi_line_with_matcher(&self.matcher));\n debug_assert!(self.is_line_by_line_fast());\n\n let mut pos = self.pos();\n while !buf[pos..].is_empty() {\n if self.has_exceeded_match_limit() {\n return Ok(None);\n }\n match self.matcher.find_candidate_line(&buf[pos..]) {\n Err(err) => return Err(S::Error::error_message(err)),\n Ok(None) => return Ok(None),\n Ok(Some(LineMatchKind::Confirmed(i))) => {\n let line = lines::locate(\n buf,\n self.config.line_term.as_byte(),\n Range::zero(i).offset(pos),\n );\n // If we matched beyond the end of the buffer, then we\n // don't report this as a match.\n if line.start() == buf.len() {\n pos = buf.len();\n continue;\n }\n return Ok(Some(line));\n }\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":522,"symbol":"sink_matched","kind":"function","lang":"rust","code":"fn sink_matched(\n &mut self,\n buf: &[u8],\n range: &Range,\n ) -> Result {\n if self.binary && self.detect_binary(buf, range)? {\n return Ok(false);\n }\n if !self.sink_break_context(range.start())? {\n return Ok(false);\n }\n self.count_lines(buf, range.start());\n let offset = self.absolute_byte_offset + range.start() as u64;\n let linebuf = &buf[*range];\n let keepgoing = self.sink.matched(\n &self.searcher,\n &SinkMatch {\n line_term: self.config.line_term,\n bytes: linebuf,\n absolute_byte_offset: offset,\n line_number: self.line_number,\n buffer: buf,\n bytes_range_in_buffer: range.start()..range.end(),\n },\n )?;\n if !keepgoing {\n return Ok(false);\n }\n self.last_line_visited = range.end();\n self.after_context_left = self.config.after_context;\n self.has_sunk = true;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":556,"symbol":"sink_before_context","kind":"function","lang":"rust","code":"fn sink_before_context(\n &mut self,\n buf: &[u8],\n range: &Range,\n ) -> Result {\n if self.binary && self.detect_binary(buf, range)? {\n return Ok(false);\n }\n self.count_lines(buf, range.start());\n let offset = self.absolute_byte_offset + range.start() as u64;\n let keepgoing = self.sink.context(\n &self.searcher,\n &SinkContext {\n #[cfg(test)]\n line_term: self.config.line_term,\n bytes: &buf[*range],\n kind: SinkContextKind::Before,\n absolute_byte_offset: offset,\n line_number: self.line_number,\n },\n )?;\n if !keepgoing {\n return Ok(false);\n }\n self.last_line_visited = range.end();\n self.has_sunk = true;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":585,"symbol":"sink_after_context","kind":"function","lang":"rust","code":"fn sink_after_context(\n &mut self,\n buf: &[u8],\n range: &Range,\n ) -> Result {\n assert!(self.after_context_left >= 1);\n\n if self.binary && self.detect_binary(buf, range)? {\n return Ok(false);\n }\n self.count_lines(buf, range.start());\n let offset = self.absolute_byte_offset + range.start() as u64;\n let keepgoing = self.sink.context(\n &self.searcher,\n &SinkContext {\n #[cfg(test)]\n line_term: self.config.line_term,\n bytes: &buf[*range],\n kind: SinkContextKind::After,\n absolute_byte_offset: offset,\n line_number: self.line_number,\n },\n )?;\n if !keepgoing {\n return Ok(false);\n }\n self.last_line_visited = range.end();\n self.after_context_left -= 1;\n self.has_sunk = true;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":617,"symbol":"sink_other_context","kind":"function","lang":"rust","code":"fn sink_other_context(\n &mut self,\n buf: &[u8],\n range: &Range,\n ) -> Result {\n if self.binary && self.detect_binary(buf, range)? {\n return Ok(false);\n }\n self.count_lines(buf, range.start());\n let offset = self.absolute_byte_offset + range.start() as u64;\n let keepgoing = self.sink.context(\n &self.searcher,\n &SinkContext {\n #[cfg(test)]\n line_term: self.config.line_term,\n bytes: &buf[*range],\n kind: SinkContextKind::Other,\n absolute_byte_offset: offset,\n line_number: self.line_number,\n },\n )?;\n if !keepgoing {\n return Ok(false);\n }\n self.last_line_visited = range.end();\n self.has_sunk = true;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":646,"symbol":"sink_break_context","kind":"function","lang":"rust","code":"fn sink_break_context(\n &mut self,\n start_of_line: usize,\n ) -> Result {\n let is_gap = self.last_line_visited < start_of_line;\n let any_context =\n self.config.before_context > 0 || self.config.after_context > 0;\n\n if !any_context || !self.has_sunk || !is_gap {\n Ok(true)\n } else {\n self.sink.context_break(&self.searcher)\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":661,"symbol":"count_lines","kind":"function","lang":"rust","code":"fn count_lines(&mut self, buf: &[u8], upto: usize) {\n if let Some(ref mut line_number) = self.line_number {\n if self.last_line_counted >= upto {\n return;\n }\n let slice = &buf[self.last_line_counted..upto];\n let count = lines::count(slice, self.config.line_term.as_byte());\n *line_number += count;\n self.last_line_counted = upto;\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":673,"symbol":"is_line_by_line_fast","kind":"function","lang":"rust","code":"fn is_line_by_line_fast(&self) -> bool {\n debug_assert!(!self.searcher.multi_line_with_matcher(&self.matcher));\n\n if self.config.passthru {\n return false;\n }\n if self.config.stop_on_nonmatch && self.has_matched {\n return false;\n }\n if let Some(line_term) = self.matcher.line_terminator() {\n // FIXME: This works around a bug in grep-regex where it does\n // not set the line terminator of the regex itself, and thus\n // line anchors like `(?m:^)` and `(?m:$)` will not match\n // anything except for `\\n`. So for now, we just disable the fast\n // line-by-line searcher which requires the regex to be able to\n // deal with line terminators correctly. The slow line-by-line\n // searcher strips line terminators and thus absolves the regex\n // engine from needing to care about whether they are `\\n` or NUL.\n if line_term.as_byte() == b'\\x00' {\n return false;\n }\n if line_term == self.config.line_term {\n return true;\n }\n }\n if let Some(non_matching) = self.matcher"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/core.rs","line":710,"symbol":"has_exceeded_match_limit","kind":"function","lang":"rust","code":"fn has_exceeded_match_limit(&self) -> bool {\n self.config.max_matches.map_or(false, |limit| self.count() >= limit)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":11,"symbol":"ReadByLine","kind":"type","lang":"rust","code":"pub(crate) struct ReadByLine<'s, M, R, S> {\n config: &'s Config,\n core: Core<'s, M, S>,\n rdr: LineBufferReader<'s, R>,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":23,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(\n searcher: &'s Searcher,\n matcher: M,\n read_from: LineBufferReader<'s, R>,\n write_to: S,\n ) -> ReadByLine<'s, M, R, S> {\n debug_assert!(!searcher.multi_line_with_matcher(&matcher));\n\n ReadByLine {\n config: &searcher.config,\n core: Core::new(searcher, matcher, write_to, false),\n rdr: read_from,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":38,"symbol":"run","kind":"function","lang":"rust","code":"pub(crate) fn run(mut self) -> Result<(), S::Error> {\n if self.core.begin()? {\n while self.fill()? {\n if !self.core.match_by_line(self.rdr.buffer())? {\n self.consume_remaining();\n break;\n }\n }\n }\n self.core.finish(\n self.rdr.absolute_byte_offset(),\n self.rdr.binary_byte_offset(),\n )\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":53,"symbol":"consume_remaining","kind":"function","lang":"rust","code":"fn consume_remaining(&mut self) {\n let consumed = self.core.pos();\n self.rdr.consume(consumed);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":58,"symbol":"fill","kind":"function","lang":"rust","code":"fn fill(&mut self) -> Result {\n assert!(self.rdr.buffer()[self.core.pos()..].is_empty());\n\n let already_binary = self.rdr.binary_byte_offset().is_some();\n let old_buf_len = self.rdr.buffer().len();\n let consumed = self.core.roll(self.rdr.buffer());\n self.rdr.consume(consumed);\n let didread = match self.rdr.fill() {\n Err(err) => return Err(S::Error::error_io(err)),\n Ok(didread) => didread,\n };\n if !already_binary {\n if let Some(offset) = self.rdr.binary_byte_offset() {\n if !self.core.binary_data(offset)? {\n return Ok(false);\n }\n }\n }\n if !didread || self.should_binary_quit() {\n return Ok(false);\n }\n // If rolling the buffer didn't result in consuming anything and if\n // re-filling the buffer didn't add any bytes, then the only thing in\n // our buffer is leftover context, which we no longer need since there\n // is nothing left to search. So forcefully quit.\n if consumed == 0 && old_buf_len == self.rdr.buffer().len() {\n self.rdr.consume(old_buf_l"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":90,"symbol":"should_binary_quit","kind":"function","lang":"rust","code":"fn should_binary_quit(&self) -> bool {\n self.rdr.binary_byte_offset().is_some()\n && self.config.binary.quit_byte().is_some()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":97,"symbol":"SliceByLine","kind":"type","lang":"rust","code":"pub(crate) struct SliceByLine<'s, M, S> {\n core: Core<'s, M, S>,\n slice: &'s [u8],\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":103,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(\n searcher: &'s Searcher,\n matcher: M,\n slice: &'s [u8],\n write_to: S,\n ) -> SliceByLine<'s, M, S> {\n debug_assert!(!searcher.multi_line_with_matcher(&matcher));\n\n SliceByLine {\n core: Core::new(searcher, matcher, write_to, true),\n slice,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":117,"symbol":"run","kind":"function","lang":"rust","code":"pub(crate) fn run(mut self) -> Result<(), S::Error> {\n if self.core.begin()? {\n let binary_upto =\n std::cmp::min(self.slice.len(), DEFAULT_BUFFER_CAPACITY);\n let binary_range = Range::new(0, binary_upto);\n if !self.core.detect_binary(self.slice, &binary_range)? {\n while !self.slice[self.core.pos()..].is_empty()\n && self.core.match_by_line(self.slice)?\n {}\n }\n }\n let byte_count = self.byte_count();\n let binary_byte_offset = self.core.binary_byte_offset();\n self.core.finish(byte_count, binary_byte_offset)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":133,"symbol":"byte_count","kind":"function","lang":"rust","code":"fn byte_count(&mut self) -> u64 {\n match self.core.binary_byte_offset() {\n Some(offset) if offset < self.core.pos() as u64 => offset,\n _ => self.core.pos() as u64,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":142,"symbol":"MultiLine","kind":"type","lang":"rust","code":"pub(crate) struct MultiLine<'s, M, S> {\n config: &'s Config,\n core: Core<'s, M, S>,\n slice: &'s [u8],\n last_match: Option,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":150,"symbol":"new","kind":"function","lang":"rust","code":"pub(crate) fn new(\n searcher: &'s Searcher,\n matcher: M,\n slice: &'s [u8],\n write_to: S,\n ) -> MultiLine<'s, M, S> {\n debug_assert!(searcher.multi_line_with_matcher(&matcher));\n\n MultiLine {\n config: &searcher.config,\n core: Core::new(searcher, matcher, write_to, true),\n slice,\n last_match: None,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":166,"symbol":"run","kind":"function","lang":"rust","code":"pub(crate) fn run(mut self) -> Result<(), S::Error> {\n if self.core.begin()? {\n let binary_upto =\n std::cmp::min(self.slice.len(), DEFAULT_BUFFER_CAPACITY);\n let binary_range = Range::new(0, binary_upto);\n if !self.core.detect_binary(self.slice, &binary_range)? {\n let mut keepgoing = true;\n while !self.slice[self.core.pos()..].is_empty() && keepgoing {\n keepgoing = self.sink()?;\n }\n if keepgoing {\n keepgoing = match self.last_match.take() {\n None => true,\n Some(last_match) => {\n if self.sink_context(&last_match)? {\n self.sink_matched(&last_match)?;\n }\n true\n }\n };\n }\n // Take care of any remaining context after the last match.\n if keepgoing {\n if self.config.passthru {\n self.core.other_context_by_line(\n self.slice,\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":208,"symbol":"sink","kind":"function","lang":"rust","code":"fn sink(&mut self) -> Result {\n if self.config.invert_match {\n return self.sink_matched_inverted();\n }\n let mat = match self.find()? {\n Some(range) => range,\n None => {\n self.core.set_pos(self.slice.len());\n return Ok(true);\n }\n };\n self.advance(&mat);\n\n let line =\n lines::locate(self.slice, self.config.line_term.as_byte(), mat);\n // We delay sinking the match to make sure we group adjacent matches\n // together in a single sink. Adjacent matches are distinct matches\n // that start and end on the same line, respectively. This guarantees\n // that a single line is never sinked more than once.\n match self.last_match.take() {\n None => {\n self.last_match = Some(line);\n Ok(true)\n }\n Some(last_match) => {\n // If the lines in the previous match overlap with the lines\n // in this match, then simply grow the match and move on. This\n // happens when the next match begins on the same line that the\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":260,"symbol":"sink_matched_inverted","kind":"function","lang":"rust","code":"fn sink_matched_inverted(&mut self) -> Result {\n assert!(self.config.invert_match);\n\n let invert_match = match self.find()? {\n None => {\n let range = Range::new(self.core.pos(), self.slice.len());\n self.core.set_pos(range.end());\n range\n }\n Some(mat) => {\n let line = lines::locate(\n self.slice,\n self.config.line_term.as_byte(),\n mat,\n );\n let range = Range::new(self.core.pos(), line.start());\n self.advance(&line);\n range\n }\n };\n if invert_match.is_empty() {\n return Ok(true);\n }\n if !self.sink_context(&invert_match)? {\n return Ok(false);\n }\n let mut stepper = LineStep::new(\n self.config.line_term.as_byte(),\n invert_match.start(),\n invert_match.end(),\n );\n while let Some(line) = stepper.next_match(self.slice) {\n if !self.sink_matched(&line)? {\n return Ok(false);\n }\n }\n Ok(true)\n"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":299,"symbol":"sink_matched","kind":"function","lang":"rust","code":"fn sink_matched(&mut self, range: &Range) -> Result {\n if range.is_empty() {\n // The only way we can produce an empty line for a match is if we\n // match the position immediately following the last byte that we\n // search, and where that last byte is also the line terminator. We\n // never want to report that match, and we know we're done at that\n // point anyway, so stop the search.\n return Ok(false);\n }\n self.core.matched(self.slice, range)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":311,"symbol":"sink_context","kind":"function","lang":"rust","code":"fn sink_context(&mut self, range: &Range) -> Result {\n if self.config.passthru {\n if !self.core.other_context_by_line(self.slice, range.start())? {\n return Ok(false);\n }\n } else {\n if !self.core.after_context_by_line(self.slice, range.start())? {\n return Ok(false);\n }\n if !self.core.before_context_by_line(self.slice, range.start())? {\n return Ok(false);\n }\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":327,"symbol":"find","kind":"function","lang":"rust","code":"fn find(&mut self) -> Result, S::Error> {\n self.core\n .find(&self.slice[self.core.pos()..])\n .map(|m| m.map(|m| m.offset(self.core.pos())))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":337,"symbol":"advance","kind":"function","lang":"rust","doc":"Advance the search position based on the previous match. If the previous match is zero width, then this advances the search position one byte past the end of the match.","code":"fn advance(&mut self, range: &Range) {\n self.core.set_pos(range.end());\n if range.is_empty() && self.core.pos() < self.slice.len() {\n let newpos = self.core.pos() + 1;\n self.core.set_pos(newpos);\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":345,"symbol":"byte_count","kind":"function","lang":"rust","code":"fn byte_count(&mut self) -> u64 {\n match self.core.binary_byte_offset() {\n Some(offset) if offset < self.core.pos() as u64 => offset,\n _ => self.core.pos() as u64,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":388,"symbol":"basic1","kind":"function","lang":"rust","code":"fn basic1() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":402,"symbol":"basic2","kind":"function","lang":"rust","code":"fn basic2() {\n let exp = \"\\nbyte count:366\\n\";\n SearcherTester::new(SHERLOCK, \"NADA\")\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":411,"symbol":"basic3","kind":"function","lang":"rust","code":"fn basic3() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n65:Holmeses, success in the province of detective work must always\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n193:can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"a\")\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":428,"symbol":"basic4","kind":"function","lang":"rust","code":"fn basic4() {\n let haystack = \"\\\na\nb\n\nc\n\n\nd\n\";\n let byte_count = haystack.len();\n let exp = format!(\"0:a\\n\\nbyte count:{}\\n\", byte_count);\n SearcherTester::new(haystack, \"a\")\n .line_number(false)\n .expected_no_line_number(&exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":447,"symbol":"invert1","kind":"function","lang":"rust","code":"fn invert1() {\n let exp = \"\\\n65:Holmeses, success in the province of detective work must always\n193:can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .line_number(false)\n .invert_match(true)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":463,"symbol":"line_number1","kind":"function","lang":"rust","code":"fn line_number1() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n\nbyte count:366\n\";\n let exp_line = \"\\\n1:0:For the Doctor Watsons of this world, as opposed to the Sherlock\n3:129:be, to a very large extent, the result of luck. Sherlock Holmes\n\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":483,"symbol":"line_number_invert1","kind":"function","lang":"rust","code":"fn line_number_invert1() {\n let exp = \"\\\n65:Holmeses, success in the province of detective work must always\n193:can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_line = \"\\\n2:65:Holmeses, success in the province of detective work must always\n4:193:can extract a clew from a wisp of straw or a flake of cigar ash;\n5:258:but Doctor Watson has to have it taken out for him and dusted,\n6:321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .invert_match(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":506,"symbol":"multi_line_overlap1","kind":"function","lang":"rust","code":"fn multi_line_overlap1() {\n let haystack = \"xxx\\nabc\\ndefxxxabc\\ndefxxx\\nxxx\";\n let byte_count = haystack.len();\n let exp = format!(\n \"4:abc\\n8:defxxxabc\\n18:defxxx\\n\\nbyte count:{}\\n\",\n byte_count\n );\n\n SearcherTester::new(haystack, \"abc\\ndef\")\n .by_line(false)\n .line_number(false)\n .expected_no_line_number(&exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":522,"symbol":"multi_line_overlap2","kind":"function","lang":"rust","code":"fn multi_line_overlap2() {\n let haystack = \"xxx\\nabc\\ndefabc\\ndefxxx\\nxxx\";\n let byte_count = haystack.len();\n let exp = format!(\n \"4:abc\\n8:defabc\\n15:defxxx\\n\\nbyte count:{}\\n\",\n byte_count\n );\n\n SearcherTester::new(haystack, \"abc\\ndef\")\n .by_line(false)\n .line_number(false)\n .expected_no_line_number(&exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":538,"symbol":"empty_line1","kind":"function","lang":"rust","code":"fn empty_line1() {\n let exp = \"\\nbyte count:0\\n\";\n SearcherTester::new(\"\", r\"^$\")\n .expected_no_line_number(exp)\n .expected_with_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":547,"symbol":"empty_line2","kind":"function","lang":"rust","code":"fn empty_line2() {\n let exp = \"0:\\n\\nbyte count:1\\n\";\n let exp_line = \"1:0:\\n\\nbyte count:1\\n\";\n\n SearcherTester::new(\"\\n\", r\"^$\")\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":558,"symbol":"empty_line3","kind":"function","lang":"rust","code":"fn empty_line3() {\n let exp = \"0:\\n1:\\n\\nbyte count:2\\n\";\n let exp_line = \"1:0:\\n2:1:\\n\\nbyte count:2\\n\";\n\n SearcherTester::new(\"\\n\\n\", r\"^$\")\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":569,"symbol":"empty_line4","kind":"function","lang":"rust","code":"fn empty_line4() {\n // See: https://github.com/BurntSushi/ripgrep/issues/441\n let haystack = \"\\\na\nb\n\nc\n\n\nd\n\";\n let byte_count = haystack.len();\n let exp = format!(\"4:\\n7:\\n8:\\n\\nbyte count:{}\\n\", byte_count);\n let exp_line =\n format!(\"3:4:\\n5:7:\\n6:8:\\n\\nbyte count:{}\\n\", byte_count);\n\n SearcherTester::new(haystack, r\"^$\")\n .expected_no_line_number(&exp)\n .expected_with_line_number(&exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":592,"symbol":"empty_line5","kind":"function","lang":"rust","code":"fn empty_line5() {\n // See: https://github.com/BurntSushi/ripgrep/issues/441\n // This is like empty_line4, but lacks the trailing line terminator.\n let haystack = \"\\\na\nb\n\nc\n\n\nd\";\n let byte_count = haystack.len();\n let exp = format!(\"4:\\n7:\\n8:\\n\\nbyte count:{}\\n\", byte_count);\n let exp_line =\n format!(\"3:4:\\n5:7:\\n6:8:\\n\\nbyte count:{}\\n\", byte_count);\n\n SearcherTester::new(haystack, r\"^$\")\n .expected_no_line_number(&exp)\n .expected_with_line_number(&exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":615,"symbol":"empty_line6","kind":"function","lang":"rust","code":"fn empty_line6() {\n // See: https://github.com/BurntSushi/ripgrep/issues/441\n // This is like empty_line4, but includes an empty line at the end.\n let haystack = \"\\\na\nb\n\nc\n\n\nd\n\n\";\n let byte_count = haystack.len();\n let exp = format!(\"4:\\n7:\\n8:\\n11:\\n\\nbyte count:{}\\n\", byte_count);\n let exp_line =\n format!(\"3:4:\\n5:7:\\n6:8:\\n8:11:\\n\\nbyte count:{}\\n\", byte_count);\n\n SearcherTester::new(haystack, r\"^$\")\n .expected_no_line_number(&exp)\n .expected_with_line_number(&exp_line)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":640,"symbol":"big1","kind":"function","lang":"rust","code":"fn big1() {\n let mut haystack = String::new();\n haystack.push_str(\"a\\n\");\n // Pick an arbitrary number above the capacity.\n for _ in 0..(4 * (DEFAULT_BUFFER_CAPACITY + 7)) {\n haystack.push_str(\"zzz\\n\");\n }\n haystack.push_str(\"a\\n\");\n\n let byte_count = haystack.len();\n let exp = format!(\"0:a\\n1048690:a\\n\\nbyte count:{}\\n\", byte_count);\n\n SearcherTester::new(&haystack, \"a\")\n .line_number(false)\n .expected_no_line_number(&exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":659,"symbol":"big_error_one_line","kind":"function","lang":"rust","code":"fn big_error_one_line() {\n let mut haystack = String::new();\n haystack.push_str(\"a\\n\");\n // Pick an arbitrary number above the capacity.\n for _ in 0..(4 * (DEFAULT_BUFFER_CAPACITY + 7)) {\n haystack.push_str(\"zzz\\n\");\n }\n haystack.push_str(\"a\\n\");\n\n let matcher = RegexMatcher::new(\"a\");\n let mut sink = KitchenSink::new();\n let mut searcher = SearcherBuilder::new()\n .heap_limit(Some(3)) // max line length is 4, one byte short\n .build();\n let result =\n searcher.search_reader(&matcher, haystack.as_bytes(), &mut sink);\n assert!(result.is_err());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":679,"symbol":"big_error_multi_line","kind":"function","lang":"rust","code":"fn big_error_multi_line() {\n let mut haystack = String::new();\n haystack.push_str(\"a\\n\");\n // Pick an arbitrary number above the capacity.\n for _ in 0..(4 * (DEFAULT_BUFFER_CAPACITY + 7)) {\n haystack.push_str(\"zzz\\n\");\n }\n haystack.push_str(\"a\\n\");\n\n let matcher = RegexMatcher::new(\"a\");\n let mut sink = KitchenSink::new();\n let mut searcher = SearcherBuilder::new()\n .multi_line(true)\n .heap_limit(Some(haystack.len())) // actually need one more byte\n .build();\n let result =\n searcher.search_reader(&matcher, haystack.as_bytes(), &mut sink);\n assert!(result.is_err());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":700,"symbol":"binary1","kind":"function","lang":"rust","code":"fn binary1() {\n let haystack = \"\\x00a\";\n let exp = \"\\nbyte count:0\\nbinary offset:0\\n\";\n\n SearcherTester::new(haystack, \"a\")\n .binary_detection(BinaryDetection::quit(0))\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":712,"symbol":"binary2","kind":"function","lang":"rust","code":"fn binary2() {\n let haystack = \"a\\x00\";\n let exp = \"\\nbyte count:0\\nbinary offset:1\\n\";\n\n SearcherTester::new(haystack, \"a\")\n .binary_detection(BinaryDetection::quit(0))\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":724,"symbol":"binary3","kind":"function","lang":"rust","code":"fn binary3() {\n let mut haystack = String::new();\n haystack.push_str(\"a\\n\");\n for _ in 0..DEFAULT_BUFFER_CAPACITY {\n haystack.push_str(\"zzz\\n\");\n }\n haystack.push_str(\"a\\n\");\n haystack.push_str(\"zzz\\n\");\n haystack.push_str(\"a\\x00a\\n\");\n haystack.push_str(\"zzz\\n\");\n haystack.push_str(\"a\\n\");\n\n // The line buffered searcher has slightly different semantics here.\n // Namely, it will *always* detect binary data in the current buffer\n // before searching it. Thus, the total number of bytes searched is\n // smaller than below.\n let exp = \"0:a\\n\\nbyte count:262146\\nbinary offset:262153\\n\";\n // In contrast, the slice readers (for multi line as well) will only\n // look for binary data in the initial chunk of bytes. After that\n // point, it only looks for binary data in matches. Note though that\n // the binary offset remains the same. (See the binary4 test for a case\n // where the offset is explicitly different.)\n let exp_slice =\n \"0:a\\n262146:a\\n\\nbyte count:262153\\nbinary offset:262153\\n\";\n\n SearcherTester::new(&haystack, \"a"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":759,"symbol":"binary4","kind":"function","lang":"rust","code":"fn binary4() {\n let mut haystack = String::new();\n haystack.push_str(\"a\\n\");\n for _ in 0..DEFAULT_BUFFER_CAPACITY {\n haystack.push_str(\"zzz\\n\");\n }\n haystack.push_str(\"a\\n\");\n // The Read searcher will detect binary data here, but since this is\n // beyond the initial buffer size and doesn't otherwise contain a\n // match, the Slice reader won't detect the binary data until the next\n // line (which is a match).\n haystack.push_str(\"b\\x00b\\n\");\n haystack.push_str(\"a\\x00a\\n\");\n haystack.push_str(\"a\\n\");\n\n let exp = \"0:a\\n\\nbyte count:262146\\nbinary offset:262149\\n\";\n // The binary offset for the Slice readers corresponds to the binary\n // data in `a\\x00a\\n` since the first line with binary data\n // (`b\\x00b\\n`) isn't part of a match, and is therefore undetected.\n let exp_slice =\n \"0:a\\n262146:a\\n\\nbyte count:262153\\nbinary offset:262153\\n\";\n\n SearcherTester::new(&haystack, \"a\")\n .binary_detection(BinaryDetection::quit(0))\n .line_number(false)\n .auto_heap_limit(false)\n .expected_no_line_number(exp)\n"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":791,"symbol":"passthru_sherlock1","kind":"function","lang":"rust","code":"fn passthru_sherlock1() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n65-Holmeses, success in the province of detective work must always\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n258-but Doctor Watson has to have it taken out for him and dusted,\n321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .passthru(true)\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":809,"symbol":"passthru_sherlock_invert1","kind":"function","lang":"rust","code":"fn passthru_sherlock_invert1() {\n let exp = \"\\\n0-For the Doctor Watsons of this world, as opposed to the Sherlock\n65:Holmeses, success in the province of detective work must always\n129-be, to a very large extent, the result of luck. Sherlock Holmes\n193:can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .passthru(true)\n .line_number(false)\n .invert_match(true)\n .expected_no_line_number(exp)\n .test();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":828,"symbol":"context_sherlock1","kind":"function","lang":"rust","code":"fn context_sherlock1() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n65-Holmeses, success in the province of detective work must always\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n\nbyte count:366\n\";\n let exp_lines = \"\\\n1:0:For the Doctor Watsons of this world, as opposed to the Sherlock\n2-65-Holmeses, success in the province of detective work must always\n3:129:be, to a very large extent, the result of luck. Sherlock Holmes\n4-193-can extract a clew from a wisp of straw or a flake of cigar ash;\n\nbyte count:366\n\";\n // before and after + line numbers\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .after_context(1)\n .before_context(1)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // after\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .after_context(1)\n .line_number(false)\n .expected_no_line_number(exp)\n .test();\n\n // before\n let exp = \"\\\n0:For th"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":877,"symbol":"context_sherlock_invert1","kind":"function","lang":"rust","code":"fn context_sherlock_invert1() {\n let exp = \"\\\n0-For the Doctor Watsons of this world, as opposed to the Sherlock\n65:Holmeses, success in the province of detective work must always\n129-be, to a very large extent, the result of luck. Sherlock Holmes\n193:can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_lines = \"\\\n1-0-For the Doctor Watsons of this world, as opposed to the Sherlock\n2:65:Holmeses, success in the province of detective work must always\n3-129-be, to a very large extent, the result of luck. Sherlock Holmes\n4:193:can extract a clew from a wisp of straw or a flake of cigar ash;\n5:258:but Doctor Watson has to have it taken out for him and dusted,\n6:321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n // before and after + line numbers\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .after_context(1)\n .before_context(1)\n .line_number(true)\n .invert_match(true)\n .expected_no_line_number(exp)\n .expected_with_line_numbe"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":932,"symbol":"context_sherlock2","kind":"function","lang":"rust","code":"fn context_sherlock2() {\n let exp = \"\\\n65-Holmeses, success in the province of detective work must always\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n193:can extract a clew from a wisp of straw or a flake of cigar ash;\n258-but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_lines = \"\\\n2-65-Holmeses, success in the province of detective work must always\n3:129:be, to a very large extent, the result of luck. Sherlock Holmes\n4:193:can extract a clew from a wisp of straw or a flake of cigar ash;\n5-258-but Doctor Watson has to have it taken out for him and dusted,\n6:321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n // before + after + line numbers\n SearcherTester::new(SHERLOCK, \" a \")\n .after_context(1)\n .before_context(1)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // before\n SearcherTester::new(SHERLOCK, \" a \")\n .before_context(1)\n .line_number(false)\n .expected"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":981,"symbol":"context_sherlock_invert2","kind":"function","lang":"rust","code":"fn context_sherlock_invert2() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n65:Holmeses, success in the province of detective work must always\n129-be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_lines = \"\\\n1:0:For the Doctor Watsons of this world, as opposed to the Sherlock\n2:65:Holmeses, success in the province of detective work must always\n3-129-be, to a very large extent, the result of luck. Sherlock Holmes\n4-193-can extract a clew from a wisp of straw or a flake of cigar ash;\n5:258:but Doctor Watson has to have it taken out for him and dusted,\n6-321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n // before + after + line numbers\n SearcherTester::new(SHERLOCK, \" a \")\n .after_context(1)\n .before_context(1)\n .line_number(true)\n .invert_match(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_l"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1046,"symbol":"context_sherlock3","kind":"function","lang":"rust","code":"fn context_sherlock3() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n65-Holmeses, success in the province of detective work must always\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n258-but Doctor Watson has to have it taken out for him and dusted,\n\nbyte count:366\n\";\n let exp_lines = \"\\\n1:0:For the Doctor Watsons of this world, as opposed to the Sherlock\n2-65-Holmeses, success in the province of detective work must always\n3:129:be, to a very large extent, the result of luck. Sherlock Holmes\n4-193-can extract a clew from a wisp of straw or a flake of cigar ash;\n5-258-but Doctor Watson has to have it taken out for him and dusted,\n\nbyte count:366\n\";\n // before and after + line numbers\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .after_context(2)\n .before_context(2)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // after\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .after_context(2)\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1097,"symbol":"context_sherlock4","kind":"function","lang":"rust","code":"fn context_sherlock4() {\n let exp = \"\\\n129-be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n258:but Doctor Watson has to have it taken out for him and dusted,\n321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_lines = \"\\\n3-129-be, to a very large extent, the result of luck. Sherlock Holmes\n4-193-can extract a clew from a wisp of straw or a flake of cigar ash;\n5:258:but Doctor Watson has to have it taken out for him and dusted,\n6-321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n // before and after + line numbers\n SearcherTester::new(SHERLOCK, \"dusted\")\n .after_context(2)\n .before_context(2)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // after\n let exp = \"\\\n258:but Doctor Watson has to have it taken out for him and dusted,\n321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n SearcherTester::new(SHERLOCK, \"dusted\")\n .after_context(2)\n .line_number(fa"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1149,"symbol":"context_sherlock5","kind":"function","lang":"rust","code":"fn context_sherlock5() {\n let exp = \"\\\n0-For the Doctor Watsons of this world, as opposed to the Sherlock\n65:Holmeses, success in the province of detective work must always\n129-be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n258-but Doctor Watson has to have it taken out for him and dusted,\n321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_lines = \"\\\n1-0-For the Doctor Watsons of this world, as opposed to the Sherlock\n2:65:Holmeses, success in the province of detective work must always\n3-129-be, to a very large extent, the result of luck. Sherlock Holmes\n4-193-can extract a clew from a wisp of straw or a flake of cigar ash;\n5-258-but Doctor Watson has to have it taken out for him and dusted,\n6:321:and exhibited clearly, with a label attached.\nbyte count:366\n\";\n // before and after + line numbers\n SearcherTester::new(SHERLOCK, \"success|attached\")\n .after_context(2)\n .before_context(2)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test("} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1210,"symbol":"context_sherlock6","kind":"function","lang":"rust","code":"fn context_sherlock6() {\n let exp = \"\\\n0:For the Doctor Watsons of this world, as opposed to the Sherlock\n65-Holmeses, success in the province of detective work must always\n129:be, to a very large extent, the result of luck. Sherlock Holmes\n193-can extract a clew from a wisp of straw or a flake of cigar ash;\n258-but Doctor Watson has to have it taken out for him and dusted,\n321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n let exp_lines = \"\\\n1:0:For the Doctor Watsons of this world, as opposed to the Sherlock\n2-65-Holmeses, success in the province of detective work must always\n3:129:be, to a very large extent, the result of luck. Sherlock Holmes\n4-193-can extract a clew from a wisp of straw or a flake of cigar ash;\n5-258-but Doctor Watson has to have it taken out for him and dusted,\n6-321-and exhibited clearly, with a label attached.\nbyte count:366\n\";\n // before and after + line numbers\n SearcherTester::new(SHERLOCK, \"Sherlock\")\n .after_context(3)\n .before_context(3)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1270,"symbol":"context_code1","kind":"function","lang":"rust","code":"fn context_code1() {\n // before and after\n let exp = \"\\\n33-\n34-fn main() {\n46: let stdin = io::stdin();\n75- let stdout = io::stdout();\n106-\n107: // Wrap the stdin reader in a Snappy reader.\n156: let mut rdr = snap::Reader::new(stdin.lock());\n207- let mut wtr = stdout.lock();\n240- io::copy(&mut rdr, &mut wtr).expect(\\\"I/O operation failed\\\");\n\nbyte count:307\n\";\n let exp_lines = \"\\\n4-33-\n5-34-fn main() {\n6:46: let stdin = io::stdin();\n7-75- let stdout = io::stdout();\n8-106-\n9:107: // Wrap the stdin reader in a Snappy reader.\n10:156: let mut rdr = snap::Reader::new(stdin.lock());\n11-207- let mut wtr = stdout.lock();\n12-240- io::copy(&mut rdr, &mut wtr).expect(\\\"I/O operation failed\\\");\n\nbyte count:307\n\";\n // before and after + line numbers\n SearcherTester::new(CODE, \"stdin\")\n .after_context(2)\n .before_context(2)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // after\n let exp = \"\\\n46: let stdin = io::stdin();\n75- let stdout = io::stdout();\n106-\n107: // Wrap the stdin reade"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1345,"symbol":"context_code2","kind":"function","lang":"rust","code":"fn context_code2() {\n let exp = \"\\\n34-fn main() {\n46- let stdin = io::stdin();\n75: let stdout = io::stdout();\n106-\n107- // Wrap the stdin reader in a Snappy reader.\n156- let mut rdr = snap::Reader::new(stdin.lock());\n207: let mut wtr = stdout.lock();\n240- io::copy(&mut rdr, &mut wtr).expect(\\\"I/O operation failed\\\");\n305-}\n\nbyte count:307\n\";\n let exp_lines = \"\\\n5-34-fn main() {\n6-46- let stdin = io::stdin();\n7:75: let stdout = io::stdout();\n8-106-\n9-107- // Wrap the stdin reader in a Snappy reader.\n10-156- let mut rdr = snap::Reader::new(stdin.lock());\n11:207: let mut wtr = stdout.lock();\n12-240- io::copy(&mut rdr, &mut wtr).expect(\\\"I/O operation failed\\\");\n13-305-}\n\nbyte count:307\n\";\n // before and after + line numbers\n SearcherTester::new(CODE, \"stdout\")\n .after_context(2)\n .before_context(2)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // after\n let exp = \"\\\n75: let stdout = io::stdout();\n106-\n107- // Wrap the stdin reader in a Snappy reader.\n--\n207: let mut wtr = stdout."} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1419,"symbol":"context_code3","kind":"function","lang":"rust","code":"fn context_code3() {\n let exp = \"\\\n20-use std::io;\n33-\n34:fn main() {\n46- let stdin = io::stdin();\n75- let stdout = io::stdout();\n106-\n107- // Wrap the stdin reader in a Snappy reader.\n156: let mut rdr = snap::Reader::new(stdin.lock());\n207- let mut wtr = stdout.lock();\n240- io::copy(&mut rdr, &mut wtr).expect(\\\"I/O operation failed\\\");\n\nbyte count:307\n\";\n let exp_lines = \"\\\n3-20-use std::io;\n4-33-\n5:34:fn main() {\n6-46- let stdin = io::stdin();\n7-75- let stdout = io::stdout();\n8-106-\n9-107- // Wrap the stdin reader in a Snappy reader.\n10:156: let mut rdr = snap::Reader::new(stdin.lock());\n11-207- let mut wtr = stdout.lock();\n12-240- io::copy(&mut rdr, &mut wtr).expect(\\\"I/O operation failed\\\");\n\nbyte count:307\n\";\n // before and after + line numbers\n SearcherTester::new(CODE, \"fn main|let mut rdr\")\n .after_context(2)\n .before_context(2)\n .line_number(true)\n .expected_no_line_number(exp)\n .expected_with_line_number(exp_lines)\n .test();\n\n // after\n let exp = \"\\\n34:fn main() {\n46- let stdin = io::stdin();\n75- let stdout = io::stdout();\n-"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1495,"symbol":"scratch","kind":"function","lang":"rust","code":"fn scratch() {\n use crate::sinks;\n use crate::testutil::RegexMatcher;\n\n const SHERLOCK: &'static [u8] = b\"\\\nFor the Doctor Wat\\xFFsons of this world, as opposed to the Sherlock\nHolmeses, success in the province of detective work must always\nbe, to a very large extent, the result of luck. Sherlock Holmes\ncan extract a clew from a wisp of straw or a flake of cigar ash;\nbut Doctor Watson has to have it taken out for him and dusted,\nand exhibited clearly, with a label attached.\\\n \";\n\n let haystack = SHERLOCK;\n let matcher = RegexMatcher::new(\"Sherlock\");\n let mut searcher = SearcherBuilder::new().line_number(true).build();\n searcher\n .search_reader(\n &matcher,\n haystack,\n sinks::Lossy(|n, line| {\n print!(\"{}:{}\", n, line);\n Ok(true)\n }),\n )\n .unwrap();\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/glue.rs","line":1525,"symbol":"regression_2260","kind":"function","lang":"rust","doc":"See: https://github.com/BurntSushi/ripgrep/issues/2260","code":"fn regression_2260() {\n use grep_regex::RegexMatcherBuilder;\n\n use crate::SearcherBuilder;\n\n let matcher = RegexMatcherBuilder::new()\n .line_terminator(Some(b'\\n'))\n .build(r\"^\\w+$\")\n .unwrap();\n let mut searcher = SearcherBuilder::new().line_number(true).build();\n\n let mut matched = false;\n searcher\n .search_slice(\n &matcher,\n b\"GATC\\n\",\n crate::sinks::UTF8(|_, _| {\n matched = true;\n Ok(true)\n }),\n )\n .unwrap();\n assert!(matched);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":13,"symbol":"MmapChoice","kind":"type","lang":"rust","doc":"If a searcher is called in circumstances where it is possible to use memory maps, and memory maps are enabled, then it will attempt to do so if it believes it will make the search faster. By default, memory maps are disabled.","code":"pub struct MmapChoice(MmapChoiceImpl);"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":16,"symbol":"MmapChoiceImpl","kind":"type","lang":"rust","code":"enum MmapChoiceImpl {\n Auto,\n Never,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":22,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> MmapChoice {\n MmapChoice(MmapChoiceImpl::Never)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":49,"symbol":"auto","kind":"function","lang":"rust","doc":"The specific contract the caller is required to uphold isn't precise, but it basically amounts to something like, \"the caller guarantees that the underlying file won't be mutated.\" This, of course, isn't feasible in many environments. However, command line tools may still decide to take the risk of, say, a `SIGBUS` occurring while attempting to read a memory map.","code":"pub unsafe fn auto() -> MmapChoice {\n MmapChoice(MmapChoiceImpl::Auto)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":54,"symbol":"never","kind":"function","lang":"rust","doc":"Never use memory maps, no matter what. This is the default.","code":"pub fn never() -> MmapChoice {\n MmapChoice(MmapChoiceImpl::Never)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":65,"symbol":"open","kind":"function","lang":"rust","doc":"memory from the given file succeeded and if memory maps are believed to be advantageous for performance. If this does attempt to open a memory map and it fails, then `None` is returned and the corresponding error (along with the file path, if present) is logged at the debug level.","code":"pub(crate) fn open(\n &self,\n file: &File,\n path: Option<&Path>,\n ) -> Option {\n if !self.is_enabled() {\n return None;\n }\n if cfg!(target_os = \"macos\") {\n // I guess memory maps on macOS aren't great.\n //\n // See: https://github.com/BurntSushi/ripgrep/issues/36\n // See: https://github.com/BurntSushi/ripgrep/pull/3246\n return None;\n }\n // SAFETY: This is acceptable because the only way `MmapChoiceImpl` can\n // be `Auto` is if the caller invoked the `auto` constructor, which\n // is itself not safe. Thus, this is a propagation of the caller's\n // assertion that using memory maps is safe.\n match unsafe { Mmap::map(file) } {\n Ok(mmap) => {\n // Hint to the kernel that we'll read sequentially. This is\n // only available on Unix.\n #[cfg(unix)]\n if let Err(err) = mmap.advise(memmap::Advice::Sequential) {\n if let Some(path) = path {\n log::debug!(\n \"{}: madvise failed: {}\",\n "} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mmap.rs","line":118,"symbol":"is_enabled","kind":"function","lang":"rust","doc":"Whether this strategy may employ memory maps or not.","code":"pub(crate) fn is_enabled(&self) -> bool {\n match self.0 {\n MmapChoiceImpl::Auto => true,\n MmapChoiceImpl::Never => false,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":55,"symbol":"BinaryDetection","kind":"type","lang":"rust","doc":"be applied to the buffer directly because binary files may not contain line terminators, which could result in exorbitant memory usage. 2. When performing a search using memory maps or by reading data off the heap, then binary detection is only guaranteed to be applied to the parts corresponding to a match. When `Quit` is enabled, then the first few KB of the data are searched for binary data.","code":"pub struct BinaryDetection(line_buffer::BinaryDetection);"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":62,"symbol":"none","kind":"function","lang":"rust","doc":"No binary detection is performed. Data reported by the searcher may contain arbitrary bytes. This is the default.","code":"pub fn none() -> BinaryDetection {\n BinaryDetection(line_buffer::BinaryDetection::None)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":79,"symbol":"quit","kind":"function","lang":"rust","doc":"When searching is performed with the entire contents mapped into memory, then binary detection is more conservative. Namely, only a fixed sized region at the beginning of the contents are detected for binary data. As a compromise, any subsequent matching (or context) lines are also searched for binary data. If binary data is detected at any point, then the search stops as if it reached EOF.","code":"pub fn quit(binary_byte: u8) -> BinaryDetection {\n BinaryDetection(line_buffer::BinaryDetection::Quit(binary_byte))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":95,"symbol":"convert","kind":"function","lang":"rust","doc":"contents of that buffer are always searched for the presence of this byte and replaced with the line terminator. In effect, the caller is guaranteed to never observe this byte while searching. When searching is performed with the entire contents mapped into memory, then this setting has no effect and is ignored.","code":"pub fn convert(binary_byte: u8) -> BinaryDetection {\n BinaryDetection(line_buffer::BinaryDetection::Convert(binary_byte))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":102,"symbol":"quit_byte","kind":"function","lang":"rust","doc":"If this binary detection uses the \"quit\" strategy, then this returns the byte that will cause a search to quit. In any other case, this returns `None`.","code":"pub fn quit_byte(&self) -> Option {\n match self.0 {\n line_buffer::BinaryDetection::Quit(b) => Some(b),\n _ => None,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":112,"symbol":"convert_byte","kind":"function","lang":"rust","doc":"If this binary detection uses the \"convert\" strategy, then this returns the byte that will be replaced by the line terminator. In any other case, this returns `None`.","code":"pub fn convert_byte(&self) -> Option {\n match self.0 {\n line_buffer::BinaryDetection::Convert(b) => Some(b),\n _ => None,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":127,"symbol":"Encoding","kind":"type","lang":"rust","doc":"An encoding to use when searching. An encoding can be used to configure a [`SearcherBuilder`] to transcode source data from an encoding to UTF-8 before searching. An `Encoding` will always be cheap to clone.","code":"pub struct Encoding(&'static encoding_rs::Encoding);"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":137,"symbol":"new","kind":"function","lang":"rust","doc":"The encoding label provided is mapped to an encoding via the set of available choices specified in the [Encoding Standard](https://encoding.spec.whatwg.org/#concept-encoding-get). If the given label does not correspond to a valid encoding, then this returns an error.","code":"pub fn new(label: &str) -> Result {\n let label = label.as_bytes();\n match encoding_rs::Encoding::for_label_no_replacement(label) {\n Some(encoding) => Ok(Encoding(encoding)),\n None => {\n Err(ConfigError::UnknownEncoding { label: label.to_vec() })\n }\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":151,"symbol":"Config","kind":"type","lang":"rust","doc":"The internal configuration of a searcher. This is shared among several search related types, but is only ever written to by the SearcherBuilder.","code":"pub struct Config {\n /// The line terminator to use.\n line_term: LineTerminator,\n /// Whether to invert matching.\n invert_match: bool,\n /// The number of lines after a match to include.\n after_context: usize,\n /// The number of lines before a match to include.\n before_context: usize,\n /// Whether to enable unbounded context or not.\n passthru: bool,\n /// Whether to count line numbers.\n line_number: bool,\n /// The maximum amount of heap memory to use.\n ///\n /// When not given, no explicit limit is enforced. When set to `0`, then\n /// only the memory map search strategy is available.\n heap_limit: Option,\n /// The memory map strategy.\n mmap: MmapChoice,\n /// The binary data detection strategy.\n binary: BinaryDetection,\n /// Whether to enable matching across multiple lines.\n multi_line: bool,\n /// An encoding that, when present, causes the searcher to transcode all\n /// input from the encoding to UTF-8.\n encoding: Option,\n /// Whether to do automatic transcoding based on a BOM or not.\n bom_sniffing: bool,\n /// Whether to stop searching when a non-matching line is found after a\n ///"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":188,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> Config {\n Config {\n line_term: LineTerminator::default(),\n invert_match: false,\n after_context: 0,\n before_context: 0,\n passthru: false,\n line_number: true,\n heap_limit: None,\n mmap: MmapChoice::default(),\n binary: BinaryDetection::default(),\n multi_line: false,\n encoding: None,\n bom_sniffing: true,\n stop_on_nonmatch: false,\n max_matches: None,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":213,"symbol":"max_context","kind":"function","lang":"rust","doc":"Return the maximal amount of lines needed to fulfill this configuration's context. If this returns `0`, then no context is ever needed.","code":"fn max_context(&self) -> usize {\n cmp::max(self.before_context, self.after_context)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":218,"symbol":"line_buffer","kind":"function","lang":"rust","doc":"Build a line buffer from this configuration.","code":"fn line_buffer(&self) -> LineBuffer {\n let mut builder = LineBufferBuilder::new();\n builder\n .line_terminator(self.line_term.as_byte())\n .binary_detection(self.binary.0);\n\n if let Some(limit) = self.heap_limit {\n let (capacity, additional) = if limit <= DEFAULT_BUFFER_CAPACITY {\n (limit, 0)\n } else {\n (DEFAULT_BUFFER_CAPACITY, limit - DEFAULT_BUFFER_CAPACITY)\n };\n builder\n .capacity(capacity)\n .buffer_alloc(BufferAllocation::Error(additional));\n }\n builder.build()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":244,"symbol":"ConfigError","kind":"type","lang":"rust","doc":"An error that can occur when building a searcher. This error occurs when a non-sensical configuration is present when trying to construct a `Searcher` from a `SearcherBuilder`.","code":"pub enum ConfigError {\n /// Indicates that the heap limit configuration prevents all possible\n /// search strategies from being used. For example, if the heap limit is\n /// set to 0 and memory map searching is disabled or unavailable.\n SearchUnavailable,\n /// Occurs when a matcher reports a line terminator that is different than\n /// the one configured in the searcher.\n MismatchedLineTerminators {\n /// The matcher's line terminator.\n matcher: LineTerminator,\n /// The searcher's line terminator.\n searcher: LineTerminator,\n },\n /// Occurs when no encoding could be found for a particular label.\n UnknownEncoding {\n /// The provided encoding label that could not be found.\n label: Vec,\n },\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":267,"symbol":"fmt","kind":"function","lang":"rust","code":"fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n match *self {\n ConfigError::SearchUnavailable => {\n write!(f, \"grep config error: no available searchers\")\n }\n ConfigError::MismatchedLineTerminators { matcher, searcher } => {\n write!(\n f,\n \"grep config error: mismatched line terminators, \\\n matcher has {:?} but searcher has {:?}\",\n matcher, searcher\n )\n }\n ConfigError::UnknownEncoding { ref label } => write!(\n f,\n \"grep config error: unknown encoding: {}\",\n String::from_utf8_lossy(label),\n ),\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":298,"symbol":"SearcherBuilder","kind":"type","lang":"rust","doc":"A search builder permits specifying the configuration of a searcher, including options like whether to invert the search or to enable multi line search. Once a searcher has been built, it is beneficial to reuse that searcher for multiple searches, if possible.","code":"pub struct SearcherBuilder {\n config: Config,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":303,"symbol":"default","kind":"function","lang":"rust","code":"fn default() -> SearcherBuilder {\n SearcherBuilder::new()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":310,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new searcher builder with a default configuration.","code":"pub fn new() -> SearcherBuilder {\n SearcherBuilder { config: Config::default() }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":315,"symbol":"build","kind":"function","lang":"rust","doc":"Build a searcher with the given matcher.","code":"pub fn build(&self) -> Searcher {\n let mut config = self.config.clone();\n if config.passthru {\n config.before_context = 0;\n config.after_context = 0;\n }\n\n let mut decode_builder = DecodeReaderBytesBuilder::new();\n decode_builder\n .encoding(self.config.encoding.as_ref().map(|e| e.0))\n .utf8_passthru(true)\n .strip_bom(self.config.bom_sniffing)\n .bom_override(true)\n .bom_sniffing(self.config.bom_sniffing);\n\n Searcher {\n config,\n decode_builder,\n decode_buffer: RefCell::new(vec![0; 8 * (1 << 10)]),\n line_buffer: RefCell::new(self.config.line_buffer()),\n multi_line_buffer: RefCell::new(vec![]),\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":346,"symbol":"line_terminator","kind":"function","lang":"rust","doc":"When using a searcher, if the matcher provided has a line terminator set, then it must be the same as this one. If they aren't, building a searcher will return an error. By default, this is set to `b'\\n'`.","code":"pub fn line_terminator(\n &mut self,\n line_term: LineTerminator,\n ) -> &mut SearcherBuilder {\n self.config.line_term = line_term;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":358,"symbol":"invert_match","kind":"function","lang":"rust","doc":"Whether to invert matching, whereby lines that don't match are reported instead of reporting lines that do match. By default, this is disabled.","code":"pub fn invert_match(&mut self, yes: bool) -> &mut SearcherBuilder {\n self.config.invert_match = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":368,"symbol":"line_number","kind":"function","lang":"rust","doc":"Whether to count and include line numbers with matching lines. This is enabled by default. There is a small performance penalty associated with computing line numbers, so this can be disabled when this isn't desirable.","code":"pub fn line_number(&mut self, yes: bool) -> &mut SearcherBuilder {\n self.config.line_number = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":388,"symbol":"multi_line","kind":"function","lang":"rust","doc":"your program's heap. However, if memory maps cannot be used (e.g., for searching streams like `stdin` or if transcoding is necessary), then the entire contents of the stream are read on to the heap before starting the search. This is disabled by default.","code":"pub fn multi_line(&mut self, yes: bool) -> &mut SearcherBuilder {\n self.config.multi_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":399,"symbol":"after_context","kind":"function","lang":"rust","doc":"Whether to include a fixed number of lines after every match. When this is set to a non-zero number, then the searcher will report `line_count` contextual lines after every match. This is set to `0` by default.","code":"pub fn after_context(\n &mut self,\n line_count: usize,\n ) -> &mut SearcherBuilder {\n self.config.after_context = line_count;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":413,"symbol":"before_context","kind":"function","lang":"rust","doc":"Whether to include a fixed number of lines before every match. When this is set to a non-zero number, then the searcher will report `line_count` contextual lines before every match. This is set to `0` by default.","code":"pub fn before_context(\n &mut self,\n line_count: usize,\n ) -> &mut SearcherBuilder {\n self.config.before_context = line_count;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":431,"symbol":"passthru","kind":"function","lang":"rust","doc":"requesting an unbounded number of before and after contextual lines. When passthru mode is enabled, any `before_context` or `after_context` settings are ignored by setting them to `0`. This is disabled by default.","code":"pub fn passthru(&mut self, yes: bool) -> &mut SearcherBuilder {\n self.config.passthru = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":457,"symbol":"heap_limit","kind":"function","lang":"rust","doc":"If a heap limit is set to `0`, then no heap space is used. If there are no alternative strategies available for searching without heap space (e.g., memory maps are disabled), then the searcher will return an error immediately. By default, no limit is set.","code":"pub fn heap_limit(\n &mut self,\n bytes: Option,\n ) -> &mut SearcherBuilder {\n self.config.heap_limit = bytes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":495,"symbol":"memory_map","kind":"function","lang":"rust","doc":"If you aren't sure whether enabling memory maps is worth it, then just don't bother with it. **WARNING**: If your process is searching a file backed memory map at the same time that file is truncated, then it's possible for the process to terminate with a bus error.","code":"pub fn memory_map(\n &mut self,\n strategy: MmapChoice,\n ) -> &mut SearcherBuilder {\n self.config.mmap = strategy;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":510,"symbol":"binary_detection","kind":"function","lang":"rust","doc":"The binary detection strategy determines not only how the searcher detects binary data, but how it responds to the presence of binary data. See the [`BinaryDetection`] type for more information. By default, binary detection is disabled.","code":"pub fn binary_detection(\n &mut self,\n detection: BinaryDetection,\n ) -> &mut SearcherBuilder {\n self.config.binary = detection;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":533,"symbol":"encoding","kind":"function","lang":"rust","doc":"used (if it's enabled, which it is, by default) to determine whether the source data is UTF-8 or UTF-16, and transcoding will be performed automatically. If no BOM could be found, then the source data is searched _as if_ it were UTF-8. However, so long as the source data is at least ASCII compatible, then it is possible for a search to produce useful results.","code":"pub fn encoding(\n &mut self,\n encoding: Option,\n ) -> &mut SearcherBuilder {\n self.config.encoding = encoding;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":553,"symbol":"bom_sniffing","kind":"function","lang":"rust","doc":"When this is disabled and if an explicit encoding is not set, then the bytes from the source stream will be passed through unchanged, including its BOM, if one is present. This is enabled by default.","code":"pub fn bom_sniffing(&mut self, yes: bool) -> &mut SearcherBuilder {\n self.config.bom_sniffing = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":563,"symbol":"stop_on_nonmatch","kind":"function","lang":"rust","doc":"Stop searching a file when a non-matching line is found after a matching line. This is useful for searching sorted files where it is expected that all the matches will be on adjacent lines.","code":"pub fn stop_on_nonmatch(\n &mut self,\n stop_on_nonmatch: bool,\n ) -> &mut SearcherBuilder {\n self.config.stop_on_nonmatch = stop_on_nonmatch;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":583,"symbol":"max_matches","kind":"function","lang":"rust","doc":"limit, regardless of how many lines it spans. Note that `0` is a legal value. This will cause the searcher to immediately quit without searching anything. By default, no limit is set.","code":"pub fn max_matches(&mut self, limit: Option) -> &mut SearcherBuilder {\n self.config.max_matches = limit;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":597,"symbol":"Searcher","kind":"type","lang":"rust","doc":"provided sink. Matches are detected via implementations of the `Matcher` trait, which must be provided by the caller when executing a search. When possible, a searcher should be reused.","code":"pub struct Searcher {\n /// The configuration for this searcher.\n ///\n /// We make most of these settings available to users of `Searcher` via\n /// public API methods, which can be queried in implementations of `Sink`\n /// if necessary.\n config: Config,\n /// A builder for constructing a streaming reader that transcodes source\n /// data according to either an explicitly specified encoding or via an\n /// automatically detected encoding via BOM sniffing.\n ///\n /// When no transcoding is needed, then the transcoder built will pass\n /// through the underlying bytes with no additional overhead.\n decode_builder: DecodeReaderBytesBuilder,\n /// A buffer that is used for transcoding scratch space.\n decode_buffer: RefCell>,\n /// A line buffer for use in line oriented searching.\n ///\n /// We wrap it in a RefCell to permit lending out borrows of `Searcher`\n /// to sinks. We still require a mutable borrow to execute a search, so\n /// we statically prevent callers from causing RefCell to panic at runtime\n /// due to a borrowing violation.\n line_buffer: RefCell,\n /// A buffer in which to store the contents of a"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":632,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new searcher with a default configuration. To configure the searcher (e.g., invert matching, enable memory maps, enable contexts, etc.), use the [`SearcherBuilder`].","code":"pub fn new() -> Searcher {\n SearcherBuilder::new().build()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":643,"symbol":"search_path","kind":"function","lang":"rust","doc":"results to the given sink. If memory maps are enabled and the searcher heuristically believes memory maps will help the search run faster, then this will use memory maps. For this reason, callers should prefer using this method or `search_file` over the more generic `search_reader` when possible.","code":"pub fn search_path(\n &mut self,\n matcher: M,\n path: P,\n write_to: S,\n ) -> Result<(), S::Error>\n where\n P: AsRef,\n M: Matcher,\n S: Sink,\n {\n let path = path.as_ref();\n let file = File::open(path).map_err(S::Error::error_io)?;\n self.search_file_maybe_path(matcher, Some(path), &file, write_to)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":665,"symbol":"search_file","kind":"function","lang":"rust","doc":"Execute a search over a file and write the results to the given sink. If memory maps are enabled and the searcher heuristically believes memory maps will help the search run faster, then this will use memory maps. For this reason, callers should prefer using this method or `search_path` over the more generic `search_reader` when possible.","code":"pub fn search_file(\n &mut self,\n matcher: M,\n file: &File,\n write_to: S,\n ) -> Result<(), S::Error>\n where\n M: Matcher,\n S: Sink,\n {\n self.search_file_maybe_path(matcher, None, file, write_to)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":678,"symbol":"search_file_maybe_path","kind":"function","lang":"rust","code":"fn search_file_maybe_path(\n &mut self,\n matcher: M,\n path: Option<&Path>,\n file: &File,\n write_to: S,\n ) -> Result<(), S::Error>\n where\n M: Matcher,\n S: Sink,\n {\n if let Some(mmap) = self.config.mmap.open(file, path) {\n log::trace!(\"{:?}: searching via memory map\", path);\n return self.search_slice(matcher, &mmap, write_to);\n }\n // Fast path for multi-line searches of files when memory maps are not\n // enabled. This pre-allocates a buffer roughly the size of the file,\n // which isn't possible when searching an arbitrary std::io::Read.\n if self.multi_line_with_matcher(&matcher) {\n log::trace!(\n \"{:?}: reading entire file on to heap for multiline\",\n path\n );\n self.fill_multi_line_buffer_from_file::(file)?;\n log::trace!(\"{:?}: searching via multiline strategy\", path);\n MultiLine::new(\n self,\n matcher,\n &*self.multi_line_buffer.borrow(),\n write_to,\n )\n .run()\n } else {\n log::t"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":727,"symbol":"search_reader","kind":"function","lang":"rust","doc":"line search is enabled---an incremental search isn't possible and the given reader is consumed completely and placed on the heap before searching begins. For this reason, when multi line search is enabled, one should try to use higher level APIs (e.g., searching by file or file path) so that memory maps can be used if they are available and enabled.","code":"pub fn search_reader(\n &mut self,\n matcher: M,\n read_from: R,\n write_to: S,\n ) -> Result<(), S::Error>\n where\n M: Matcher,\n R: io::Read,\n S: Sink,\n {\n self.check_config(&matcher).map_err(S::Error::error_config)?;\n\n let mut decode_buffer = self.decode_buffer.borrow_mut();\n let decoder = self\n .decode_builder\n .build_with_buffer(read_from, &mut *decode_buffer)\n .map_err(S::Error::error_io)?;\n\n if self.multi_line_with_matcher(&matcher) {\n log::trace!(\n \"generic reader: reading everything to heap for multiline\"\n );\n self.fill_multi_line_buffer_from_reader::<_, S>(decoder)?;\n log::trace!(\"generic reader: searching via multiline strategy\");\n MultiLine::new(\n self,\n matcher,\n &*self.multi_line_buffer.borrow(),\n write_to,\n )\n .run()\n } else {\n let mut line_buffer = self.line_buffer.borrow_mut();\n let rdr = LineBufferReader::new(decoder, &mut *line_buffer);\n log::trace!(\"gener"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":769,"symbol":"search_slice","kind":"function","lang":"rust","doc":"Execute a search over the given slice and write the results to the given sink.","code":"pub fn search_slice(\n &mut self,\n matcher: M,\n slice: &[u8],\n write_to: S,\n ) -> Result<(), S::Error>\n where\n M: Matcher,\n S: Sink,\n {\n self.check_config(&matcher).map_err(S::Error::error_config)?;\n\n // We can search the slice directly, unless we need to do transcoding.\n if self.slice_needs_transcoding(slice) {\n log::trace!(\n \"slice reader: needs transcoding, using generic reader\"\n );\n return self.search_reader(matcher, slice, write_to);\n }\n if self.multi_line_with_matcher(&matcher) {\n log::trace!(\"slice reader: searching via multiline strategy\");\n MultiLine::new(self, matcher, slice, write_to).run()\n } else {\n log::trace!(\"slice reader: searching via slice-by-line strategy\");\n SliceByLine::new(self, matcher, slice, write_to).run()\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":798,"symbol":"set_binary_detection","kind":"function","lang":"rust","doc":"Set the binary detection method used on this searcher.","code":"pub fn set_binary_detection(&mut self, detection: BinaryDetection) {\n self.config.binary = detection.clone();\n self.line_buffer.borrow_mut().set_binary_detection(detection.0);\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":805,"symbol":"check_config","kind":"function","lang":"rust","doc":"Check that the searcher's configuration and the matcher are consistent with each other.","code":"fn check_config(&self, matcher: M) -> Result<(), ConfigError> {\n if self.config.heap_limit == Some(0) && !self.config.mmap.is_enabled()\n {\n return Err(ConfigError::SearchUnavailable);\n }\n let matcher_line_term = match matcher.line_terminator() {\n None => return Ok(()),\n Some(line_term) => line_term,\n };\n if matcher_line_term != self.config.line_term {\n return Err(ConfigError::MismatchedLineTerminators {\n matcher: matcher_line_term,\n searcher: self.config.line_term,\n });\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":824,"symbol":"slice_needs_transcoding","kind":"function","lang":"rust","doc":"Returns true if and only if the given slice needs to be transcoded.","code":"fn slice_needs_transcoding(&self, slice: &[u8]) -> bool {\n self.config.encoding.is_some()\n || (self.config.bom_sniffing && slice_has_bom(slice))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":836,"symbol":"line_terminator","kind":"function","lang":"rust","doc":"Returns the line terminator used by this searcher.","code":"pub fn line_terminator(&self) -> LineTerminator {\n self.config.line_term\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":842,"symbol":"binary_detection","kind":"function","lang":"rust","doc":"Returns the type of binary detection configured on this searcher.","code":"pub fn binary_detection(&self) -> &BinaryDetection {\n &self.config.binary\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":850,"symbol":"invert_match","kind":"function","lang":"rust","doc":"Returns true if and only if this searcher is configured to invert its search results. That is, matching lines are lines that do **not** match the searcher's matcher.","code":"pub fn invert_match(&self) -> bool {\n self.config.invert_match\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":857,"symbol":"line_number","kind":"function","lang":"rust","doc":"Returns true if and only if this searcher is configured to count line numbers.","code":"pub fn line_number(&self) -> bool {\n self.config.line_number\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":864,"symbol":"multi_line","kind":"function","lang":"rust","doc":"Returns true if and only if this searcher is configured to perform multi line search.","code":"pub fn multi_line(&self) -> bool {\n self.config.multi_line\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":871,"symbol":"stop_on_nonmatch","kind":"function","lang":"rust","doc":"Returns true if and only if this searcher is configured to stop when it finds a non-matching line after a matching one.","code":"pub fn stop_on_nonmatch(&self) -> bool {\n self.config.stop_on_nonmatch\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":885,"symbol":"max_matches","kind":"function","lang":"rust","doc":"If multi line search is enabled and a match spans multiple lines, then that match is counted exactly once for the purposes of enforcing this limit, regardless of how many lines it spans. Note that `0` is a legal value. This will cause the searcher to immediately quit without searching anything.","code":"pub fn max_matches(&self) -> Option {\n self.config.max_matches\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":896,"symbol":"multi_line_with_matcher","kind":"function","lang":"rust","doc":"strategy given the provided matcher. This may diverge from the result of `multi_line` in cases where the searcher has been configured to execute a search that can report matches over multiple lines, but where the matcher guarantees that it will never produce a match over multiple lines.","code":"pub fn multi_line_with_matcher(&self, matcher: M) -> bool {\n if !self.multi_line() {\n return false;\n }\n if let Some(line_term) = matcher.line_terminator() {\n if line_term == self.line_terminator() {\n return false;\n }\n }\n if let Some(non_matching) = matcher.non_matching_bytes() {\n // If the line terminator is CRLF, we don't actually need to care\n // whether the regex can match `\\r` or not. Namely, a `\\r` is\n // neither necessary nor sufficient to terminate a line. A `\\n` is\n // always required.\n if non_matching.contains(self.line_terminator().as_byte()) {\n return false;\n }\n }\n true\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":920,"symbol":"after_context","kind":"function","lang":"rust","doc":"Returns the number of \"after\" context lines to report. When context reporting is not enabled, this returns `0`.","code":"pub fn after_context(&self) -> usize {\n self.config.after_context\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":927,"symbol":"before_context","kind":"function","lang":"rust","doc":"Returns the number of \"before\" context lines to report. When context reporting is not enabled, this returns `0`.","code":"pub fn before_context(&self) -> usize {\n self.config.before_context\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":933,"symbol":"passthru","kind":"function","lang":"rust","doc":"Returns true if and only if the searcher has \"passthru\" mode enabled.","code":"pub fn passthru(&self) -> bool {\n self.config.passthru\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":940,"symbol":"fill_multi_line_buffer_from_file","kind":"function","lang":"rust","doc":"Fill the buffer for use with multi-line searching from the given file. This reads from the file until EOF or until an error occurs. If the contents exceed the configured heap limit, then an error is returned.","code":"fn fill_multi_line_buffer_from_file(\n &self,\n file: &File,\n ) -> Result<(), S::Error> {\n assert!(self.config.multi_line);\n\n let mut decode_buffer = self.decode_buffer.borrow_mut();\n let mut read_from = self\n .decode_builder\n .build_with_buffer(file, &mut *decode_buffer)\n .map_err(S::Error::error_io)?;\n\n // If we don't have a heap limit, then we can defer to std's\n // read_to_end implementation. fill_multi_line_buffer_from_reader will\n // do this too, but since we have a File, we can be a bit smarter about\n // pre-allocating here.\n //\n // If we're transcoding, then our pre-allocation might not be exact,\n // but is probably still better than nothing.\n if self.config.heap_limit.is_none() {\n let mut buf = self.multi_line_buffer.borrow_mut();\n buf.clear();\n let cap =\n file.metadata().map(|m| m.len() as usize + 1).unwrap_or(0);\n buf.reserve(cap);\n read_from.read_to_end(&mut *buf).map_err(S::Error::error_io)?;\n return Ok(());\n }\n self.fill_multi_line_buffer_from"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":975,"symbol":"fill_multi_line_buffer_from_reader","kind":"function","lang":"rust","doc":"Fill the buffer for use with multi-line searching from the given reader. This reads from the reader until EOF or until an error occurs. If the contents exceed the configured heap limit, then an error is returned.","code":"fn fill_multi_line_buffer_from_reader(\n &self,\n mut read_from: R,\n ) -> Result<(), S::Error> {\n assert!(self.config.multi_line);\n\n let mut buf = self.multi_line_buffer.borrow_mut();\n buf.clear();\n\n // If we don't have a heap limit, then we can defer to std's\n // read_to_end implementation...\n let heap_limit = match self.config.heap_limit {\n Some(heap_limit) => heap_limit,\n None => {\n read_from\n .read_to_end(&mut *buf)\n .map_err(S::Error::error_io)?;\n return Ok(());\n }\n };\n if heap_limit == 0 {\n return Err(S::Error::error_io(alloc_error(heap_limit)));\n }\n\n // ... otherwise we need to roll our own. This is likely quite a bit\n // slower than what is optimal, but we avoid worry about memory safety\n // until there's a compelling reason to speed this up.\n buf.resize(cmp::min(DEFAULT_BUFFER_CAPACITY, heap_limit), 0);\n let mut pos = 0;\n loop {\n let nread = match read_from.read(&mut buf[pos..]) {\n Ok(nread) => nre"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":1036,"symbol":"slice_has_bom","kind":"function","lang":"rust","doc":"Returns true if and only if the given slice begins with a UTF-8 or UTF-16 BOM. This is used by the searcher to determine if a transcoder is necessary. Otherwise, it is advantageous to search the slice directly.","code":"fn slice_has_bom(slice: &[u8]) -> bool {\n let enc = match encoding_rs::Encoding::for_bom(slice) {\n None => return false,\n Some((enc, _)) => enc,\n };\n log::trace!(\"found byte-order mark (BOM) for encoding {enc:?}\");\n [encoding_rs::UTF_16LE, encoding_rs::UTF_16BE, encoding_rs::UTF_8]\n .contains(&enc)\n}"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":1053,"symbol":"config_error_heap_limit","kind":"function","lang":"rust","code":"fn config_error_heap_limit() {\n let matcher = RegexMatcher::new(\"\");\n let sink = KitchenSink::new();\n let mut searcher = SearcherBuilder::new().heap_limit(Some(0)).build();\n let res = searcher.search_slice(matcher, &[], sink);\n assert!(res.is_err());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":1062,"symbol":"config_error_line_terminator","kind":"function","lang":"rust","code":"fn config_error_line_terminator() {\n let mut matcher = RegexMatcher::new(\"\");\n matcher.set_line_term(Some(LineTerminator::byte(b'z')));\n\n let sink = KitchenSink::new();\n let mut searcher = Searcher::new();\n let res = searcher.search_slice(matcher, &[], sink);\n assert!(res.is_err());\n }"} {"repo":"ripgrep","file":"crates/searcher/src/searcher/mod.rs","line":1073,"symbol":"uft8_bom_sniffing","kind":"function","lang":"rust","code":"fn uft8_bom_sniffing() {\n // See: https://github.com/BurntSushi/ripgrep/issues/1638\n // ripgrep must sniff utf-8 BOM, just like it does with utf-16\n let matcher = RegexMatcher::new(\"foo\");\n let haystack: &[u8] = &[0xef, 0xbb, 0xbf, 0x66, 0x6f, 0x6f];\n\n let mut sink = KitchenSink::new();\n let mut searcher = SearcherBuilder::new().build();\n\n let res = searcher.search_slice(matcher, haystack, &mut sink);\n assert!(res.is_ok());\n\n let sink_output = String::from_utf8(sink.as_bytes().to_vec()).unwrap();\n assert_eq!(sink_output, \"1:0:foo\\nbyte count:3\\n\");\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":18,"symbol":"SinkError","kind":"type","lang":"rust","doc":"Unless you have a specialized use case, you probably don't need to implement this trait explicitly. It's likely that using `std::io::Error` (which implements this trait) for your error type is good enough, largely because most errors that occur during search will likely be an `std::io::Error`.","code":"pub trait SinkError: Sized {\n /// A constructor for converting any value that satisfies the\n /// `std::fmt::Display` trait into an error.\n fn error_message(message: T) -> Self;\n\n /// A constructor for converting I/O errors that occur while searching into\n /// an error of this type.\n ///\n /// By default, this is implemented via the `error_message` constructor.\n fn error_io(err: io::Error) -> Self {\n Self::error_message(err)\n }\n\n /// A constructor for converting configuration errors that occur while\n /// building a searcher into an error of this type.\n ///\n /// By default, this is implemented via the `error_message` constructor.\n fn error_config(err: ConfigError) -> Self {\n Self::error_message(err)\n }\n}"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":21,"symbol":"error_message","kind":"function","lang":"rust","doc":"A constructor for converting any value that satisfies the `std::fmt::Display` trait into an error.","code":"fn error_message(message: T) -> Self;"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":27,"symbol":"error_io","kind":"function","lang":"rust","doc":"A constructor for converting I/O errors that occur while searching into an error of this type. By default, this is implemented via the `error_message` constructor.","code":"fn error_io(err: io::Error) -> Self {\n Self::error_message(err)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":35,"symbol":"error_config","kind":"function","lang":"rust","doc":"A constructor for converting configuration errors that occur while building a searcher into an error of this type. By default, this is implemented via the `error_message` constructor.","code":"fn error_config(err: ConfigError) -> Self {\n Self::error_message(err)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":43,"symbol":"error_message","kind":"function","lang":"rust","code":"fn error_message(message: T) -> io::Error {\n io::Error::new(io::ErrorKind::Other, message.to_string())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":47,"symbol":"error_io","kind":"function","lang":"rust","code":"fn error_io(err: io::Error) -> io::Error {\n err\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":55,"symbol":"error_message","kind":"function","lang":"rust","code":"fn error_message(\n message: T,\n ) -> Box {\n Box::::from(message.to_string())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":102,"symbol":"Sink","kind":"type","lang":"rust","doc":"When errors are reported (whether in the searcher or in the implementation of `Sink`), then searchers quit immediately without calling `finish`. For simpler uses of `Sink`, callers may elect to use one of the more convenient but less flexible implementations in the [`sinks`] module.","code":"pub trait Sink {\n /// The type of an error that should be reported by a searcher.\n ///\n /// Errors of this type are not only returned by the methods on this\n /// trait, but the constructors defined in `SinkError` are also used in\n /// the searcher implementation itself. e.g., When a I/O error occurs when\n /// reading data from a file.\n type Error: SinkError;\n\n /// This method is called whenever a match is found.\n ///\n /// If multi line is enabled on the searcher, then the match reported here\n /// may span multiple lines and it may include multiple matches. When multi\n /// line is disabled, then the match is guaranteed to span exactly one\n /// non-empty line (where a single line is, at minimum, a line terminator).\n ///\n /// If this returns `true`, then searching continues. If this returns\n /// `false`, then searching is stopped immediately and `finish` is called.\n ///\n /// If this returns an error, then searching is stopped immediately,\n /// `finish` is not called and the error is bubbled back up to the caller\n /// of the searcher.\n fn matched(\n &mut self,\n _searcher: &Searcher,\n _mat: &SinkMatch<'_>"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":124,"symbol":"matched","kind":"function","lang":"rust","doc":"If this returns `true`, then searching continues. If this returns `false`, then searching is stopped immediately and `finish` is called. If this returns an error, then searching is stopped immediately, `finish` is not called and the error is bubbled back up to the caller of the searcher.","code":"fn matched(\n &mut self,\n _searcher: &Searcher,\n _mat: &SinkMatch<'_>,\n ) -> Result;"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":143,"symbol":"context","kind":"function","lang":"rust","doc":"If this returns `true`, then searching continues. If this returns `false`, then searching is stopped immediately and `finish` is called. If this returns an error, then searching is stopped immediately, `finish` is not called and the error is bubbled back up to the caller of the searcher.","code":"fn context(\n &mut self,\n _searcher: &Searcher,\n _context: &SinkContext<'_>,\n ) -> Result {\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":167,"symbol":"context_break","kind":"function","lang":"rust","doc":"If this returns `true`, then searching continues. If this returns `false`, then searching is stopped immediately and `finish` is called. If this returns an error, then searching is stopped immediately, `finish` is not called and the error is bubbled back up to the caller of the searcher.","code":"fn context_break(\n &mut self,\n _searcher: &Searcher,\n ) -> Result {\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":188,"symbol":"binary_data","kind":"function","lang":"rust","doc":"If this returns an error, then searching is stopped immediately, `finish` is not called and the error is bubbled back up to the caller of the searcher. By default, it does nothing and returns `true`.","code":"fn binary_data(\n &mut self,\n _searcher: &Searcher,\n _binary_byte_offset: u64,\n ) -> Result {\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":206,"symbol":"begin","kind":"function","lang":"rust","doc":"If this returns `true`, then searching continues. If this returns `false`, then searching is stopped immediately and `finish` is called. If this returns an error, then searching is stopped immediately, `finish` is not called and the error is bubbled back up to the caller of the searcher.","code":"fn begin(&mut self, _searcher: &Searcher) -> Result {\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":216,"symbol":"finish","kind":"function","lang":"rust","doc":"This method is called when a search has completed. By default, this does nothing. If this returns an error, the error is bubbled back up to the caller of the searcher.","code":"fn finish(\n &mut self,\n _searcher: &Searcher,\n _: &SinkFinish,\n ) -> Result<(), Self::Error> {\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":229,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n (**self).matched(searcher, mat)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":238,"symbol":"context","kind":"function","lang":"rust","code":"fn context(\n &mut self,\n searcher: &Searcher,\n context: &SinkContext<'_>,\n ) -> Result {\n (**self).context(searcher, context)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":247,"symbol":"context_break","kind":"function","lang":"rust","code":"fn context_break(\n &mut self,\n searcher: &Searcher,\n ) -> Result {\n (**self).context_break(searcher)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":255,"symbol":"binary_data","kind":"function","lang":"rust","code":"fn binary_data(\n &mut self,\n searcher: &Searcher,\n binary_byte_offset: u64,\n ) -> Result {\n (**self).binary_data(searcher, binary_byte_offset)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":264,"symbol":"begin","kind":"function","lang":"rust","code":"fn begin(&mut self, searcher: &Searcher) -> Result {\n (**self).begin(searcher)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":269,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(\n &mut self,\n searcher: &Searcher,\n sink_finish: &SinkFinish,\n ) -> Result<(), S::Error> {\n (**self).finish(searcher, sink_finish)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":282,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n (**self).matched(searcher, mat)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":291,"symbol":"context","kind":"function","lang":"rust","code":"fn context(\n &mut self,\n searcher: &Searcher,\n context: &SinkContext<'_>,\n ) -> Result {\n (**self).context(searcher, context)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":300,"symbol":"context_break","kind":"function","lang":"rust","code":"fn context_break(\n &mut self,\n searcher: &Searcher,\n ) -> Result {\n (**self).context_break(searcher)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":308,"symbol":"binary_data","kind":"function","lang":"rust","code":"fn binary_data(\n &mut self,\n searcher: &Searcher,\n binary_byte_offset: u64,\n ) -> Result {\n (**self).binary_data(searcher, binary_byte_offset)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":317,"symbol":"begin","kind":"function","lang":"rust","code":"fn begin(&mut self, searcher: &Searcher) -> Result {\n (**self).begin(searcher)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":322,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(\n &mut self,\n searcher: &Searcher,\n sink_finish: &SinkFinish,\n ) -> Result<(), S::Error> {\n (**self).finish(searcher, sink_finish)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":340,"symbol":"SinkFinish","kind":"type","lang":"rust","doc":"This reports data such as the total number of bytes searched and the absolute offset of the first occurrence of binary data, if any were found. A searcher that stops early because of an error does not call `finish`. A searcher that stops early because the `Sink` implementor instructed it to will still call `finish`.","code":"pub struct SinkFinish {\n pub(crate) byte_count: u64,\n pub(crate) binary_byte_offset: Option,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":348,"symbol":"byte_count","kind":"function","lang":"rust","doc":"Return the total number of bytes searched.","code":"pub fn byte_count(&self) -> u64 {\n self.byte_count\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":359,"symbol":"binary_byte_offset","kind":"function","lang":"rust","doc":"If binary detection is enabled and if binary data was found, then this returns the absolute byte offset of the first detected byte of binary data. Note that since this is an absolute byte offset, it cannot be relied upon to index into any addressable memory.","code":"pub fn binary_byte_offset(&self) -> Option {\n self.binary_byte_offset\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":366,"symbol":"SinkMatch","kind":"type","lang":"rust","doc":"A type that describes a match reported by a searcher.","code":"pub struct SinkMatch<'b> {\n pub(crate) line_term: LineTerminator,\n pub(crate) bytes: &'b [u8],\n pub(crate) absolute_byte_offset: u64,\n pub(crate) line_number: Option,\n pub(crate) buffer: &'b [u8],\n pub(crate) bytes_range_in_buffer: std::ops::Range,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":379,"symbol":"bytes","kind":"function","lang":"rust","doc":"Returns the bytes for all matching lines, including the line terminators, if they exist.","code":"pub fn bytes(&self) -> &'b [u8] {\n self.bytes\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":392,"symbol":"lines","kind":"function","lang":"rust","doc":"If multi line search is enabled, then this may yield more than one line (but always at least one line). If multi line search is disabled, then this always reports exactly one line (but may consist of just the line terminator). Lines yielded by this iterator include their terminators.","code":"pub fn lines(&self) -> LineIter<'b> {\n LineIter::new(self.line_term.as_byte(), self.bytes)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":401,"symbol":"absolute_byte_offset","kind":"function","lang":"rust","doc":"Returns the absolute byte offset of the start of this match. This offset is absolute in that it is relative to the very beginning of the input in a search, and can never be relied upon to be a valid index into an in-memory slice.","code":"pub fn absolute_byte_offset(&self) -> u64 {\n self.absolute_byte_offset\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":410,"symbol":"line_number","kind":"function","lang":"rust","doc":"Returns the line number of the first line in this match, if available. Line numbers are only available when the search builder is instructed to compute them.","code":"pub fn line_number(&self) -> Option {\n self.line_number\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":416,"symbol":"buffer","kind":"function","lang":"rust","doc":"Exposes as much of the underlying buffer that was search as possible.","code":"pub fn buffer(&self) -> &'b [u8] {\n self.buffer\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":423,"symbol":"bytes_range_in_buffer","kind":"function","lang":"rust","doc":"Returns a range that corresponds to where [`SinkMatch::bytes`] appears in [`SinkMatch::buffer`].","code":"pub fn bytes_range_in_buffer(&self) -> std::ops::Range {\n self.bytes_range_in_buffer.clone()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":430,"symbol":"SinkContextKind","kind":"type","lang":"rust","doc":"The type of context reported by a searcher.","code":"pub enum SinkContextKind {\n /// The line reported occurred before a match.\n Before,\n /// The line reported occurred after a match.\n After,\n /// Any other type of context reported, e.g., as a result of a searcher's\n /// \"passthru\" mode.\n Other,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":442,"symbol":"SinkContext","kind":"type","lang":"rust","doc":"A type that describes a contextual line reported by a searcher.","code":"pub struct SinkContext<'b> {\n #[cfg(test)]\n pub(crate) line_term: LineTerminator,\n pub(crate) bytes: &'b [u8],\n pub(crate) kind: SinkContextKind,\n pub(crate) absolute_byte_offset: u64,\n pub(crate) line_number: Option,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":454,"symbol":"bytes","kind":"function","lang":"rust","doc":"Returns the context bytes, including line terminators.","code":"pub fn bytes(&self) -> &'b [u8] {\n self.bytes\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":460,"symbol":"kind","kind":"function","lang":"rust","doc":"Returns the type of context.","code":"pub fn kind(&self) -> &SinkContextKind {\n &self.kind\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":471,"symbol":"lines","kind":"function","lang":"rust","doc":"Return an iterator over the lines in this match. This always yields exactly one line (and that one line may contain just the line terminator). Lines yielded by this iterator include their terminators.","code":"pub(crate) fn lines(&self) -> LineIter<'b> {\n LineIter::new(self.line_term.as_byte(), self.bytes)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":480,"symbol":"absolute_byte_offset","kind":"function","lang":"rust","doc":"Returns the absolute byte offset of the start of this context. This offset is absolute in that it is relative to the very beginning of the input in a search, and can never be relied upon to be a valid index into an in-memory slice.","code":"pub fn absolute_byte_offset(&self) -> u64 {\n self.absolute_byte_offset\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":490,"symbol":"line_number","kind":"function","lang":"rust","doc":"Returns the line number of the first line in this context, if available. Line numbers are only available when the search builder is instructed to compute them.","code":"pub fn line_number(&self) -> Option {\n self.line_number\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":540,"symbol":"UTF8","kind":"type","lang":"rust","doc":"containing the matched data. The closure returns a `Result`. If the `bool` is `false`, then the search stops immediately. Otherwise, searching continues. If multi line mode was enabled, the line number refers to the line number of the first line in the match.","code":"pub struct UTF8(pub F)\n where\n F: FnMut(u64, &str) -> Result;"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":550,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n _searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n let matched = match std::str::from_utf8(mat.bytes()) {\n Ok(matched) => matched,\n Err(err) => return Err(io::Error::error_message(err)),\n };\n let line_number = match mat.line_number() {\n Some(line_number) => line_number,\n None => {\n let msg = \"line numbers not enabled\";\n return Err(io::Error::error_message(msg));\n }\n };\n (self.0)(line_number, &matched)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":588,"symbol":"Lossy","kind":"type","lang":"rust","doc":"containing the matched data. The closure returns a `Result`. If the `bool` is `false`, then the search stops immediately. Otherwise, searching continues. If multi line mode was enabled, the line number refers to the line number of the first line in the match.","code":"pub struct Lossy(pub F)\n where\n F: FnMut(u64, &str) -> Result;"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":598,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n _searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n use std::borrow::Cow;\n\n let matched = match std::str::from_utf8(mat.bytes()) {\n Ok(matched) => Cow::Borrowed(matched),\n // TODO: In theory, it should be possible to amortize\n // allocation here, but `std` doesn't provide such an API.\n // Regardless, this only happens on matches with invalid UTF-8,\n // which should be pretty rare.\n Err(_) => String::from_utf8_lossy(mat.bytes()),\n };\n let line_number = match mat.line_number() {\n Some(line_number) => line_number,\n None => {\n let msg = \"line numbers not enabled\";\n return Err(io::Error::error_message(msg));\n }\n };\n (self.0)(line_number, &matched)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":638,"symbol":"Bytes","kind":"type","lang":"rust","doc":"containing the matched data. The closure returns a `Result`. If the `bool` is `false`, then the search stops immediately. Otherwise, searching continues. If multi line mode was enabled, the line number refers to the line number of the first line in the match.","code":"pub struct Bytes(pub F)\n where\n F: FnMut(u64, &[u8]) -> Result;"} {"repo":"ripgrep","file":"crates/searcher/src/sink.rs","line":648,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n _searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n let line_number = match mat.line_number() {\n Some(line_number) => line_number,\n None => {\n let msg = \"line numbers not enabled\";\n return Err(io::Error::error_message(msg));\n }\n };\n (self.0)(line_number, mat.bytes())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":24,"symbol":"RegexMatcher","kind":"type","lang":"rust","doc":"This supports setting the matcher's line terminator configuration directly, which we use for testing purposes. That is, the caller explicitly determines whether the line terminator optimization is enabled. (In reality this optimization is detected automatically by inspecting and possibly modifying the regex itself.)","code":"pub(crate) struct RegexMatcher {\n regex: Regex,\n line_term: Option,\n every_line_is_candidate: bool,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":32,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new regex matcher.","code":"pub(crate) fn new(pattern: &str) -> RegexMatcher {\n let regex = RegexBuilder::new(pattern)\n .multi_line(true) // permits ^ and $ to match at \\n boundaries\n .build()\n .unwrap();\n RegexMatcher { regex, line_term: None, every_line_is_candidate: false }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":43,"symbol":"set_line_term","kind":"function","lang":"rust","doc":"Forcefully set the line terminator of this matcher. By default, this matcher has no line terminator set.","code":"pub(crate) fn set_line_term(\n &mut self,\n line_term: Option,\n ) -> &mut RegexMatcher {\n self.line_term = line_term;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":54,"symbol":"every_line_is_candidate","kind":"function","lang":"rust","doc":"Whether to return every line as a candidate or not. This forces searchers to handle the case of reporting a false positive.","code":"pub(crate) fn every_line_is_candidate(\n &mut self,\n yes: bool,\n ) -> &mut RegexMatcher {\n self.every_line_is_candidate = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":67,"symbol":"find_at","kind":"function","lang":"rust","code":"fn find_at(\n &self,\n haystack: &[u8],\n at: usize,\n ) -> Result, NoError> {\n Ok(self\n .regex\n .find_at(haystack, at)\n .map(|m| Match::new(m.start(), m.end())))\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":78,"symbol":"new_captures","kind":"function","lang":"rust","code":"fn new_captures(&self) -> Result {\n Ok(NoCaptures::new())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":82,"symbol":"line_terminator","kind":"function","lang":"rust","code":"fn line_terminator(&self) -> Option {\n self.line_term\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":86,"symbol":"find_candidate_line","kind":"function","lang":"rust","code":"fn find_candidate_line(\n &self,\n haystack: &[u8],\n ) -> Result, NoError> {\n if self.every_line_is_candidate {\n assert!(self.line_term.is_some());\n if haystack.is_empty() {\n return Ok(None);\n }\n // Make it interesting and return the last byte in the current\n // line.\n let i = haystack\n .find_byte(self.line_term.unwrap().as_byte())\n .map(|i| i)\n .unwrap_or(haystack.len() - 1);\n Ok(Some(LineMatchKind::Candidate(i)))\n } else {\n Ok(self.shortest_match(haystack)?.map(LineMatchKind::Confirmed))\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":113,"symbol":"KitchenSink","kind":"type","lang":"rust","doc":"An implementation of Sink that prints all available information. This is useful for tests because it lets us easily confirm whether data is being passed to Sink correctly.","code":"pub(crate) struct KitchenSink(Vec);"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":118,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new implementation of Sink that includes everything in the kitchen.","code":"pub(crate) fn new() -> KitchenSink {\n KitchenSink(vec![])\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":123,"symbol":"as_bytes","kind":"function","lang":"rust","doc":"Return the data written to this sink.","code":"pub(crate) fn as_bytes(&self) -> &[u8] {\n &self.0\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":131,"symbol":"matched","kind":"function","lang":"rust","code":"fn matched(\n &mut self,\n _searcher: &Searcher,\n mat: &SinkMatch<'_>,\n ) -> Result {\n assert!(!mat.bytes().is_empty());\n assert!(mat.lines().count() >= 1);\n\n let mut line_number = mat.line_number();\n let mut byte_offset = mat.absolute_byte_offset();\n for line in mat.lines() {\n if let Some(ref mut n) = line_number {\n write!(self.0, \"{}:\", n)?;\n *n += 1;\n }\n\n write!(self.0, \"{}:\", byte_offset)?;\n byte_offset += line.len() as u64;\n self.0.write_all(line)?;\n }\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":154,"symbol":"context","kind":"function","lang":"rust","code":"fn context(\n &mut self,\n _searcher: &Searcher,\n context: &SinkContext<'_>,\n ) -> Result {\n assert!(!context.bytes().is_empty());\n assert!(context.lines().count() == 1);\n\n if let Some(line_number) = context.line_number() {\n write!(self.0, \"{}-\", line_number)?;\n }\n write!(self.0, \"{}-\", context.absolute_byte_offset)?;\n self.0.write_all(context.bytes())?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":170,"symbol":"context_break","kind":"function","lang":"rust","code":"fn context_break(\n &mut self,\n _searcher: &Searcher,\n ) -> Result {\n self.0.write_all(b\"--\\n\")?;\n Ok(true)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":178,"symbol":"finish","kind":"function","lang":"rust","code":"fn finish(\n &mut self,\n _searcher: &Searcher,\n sink_finish: &SinkFinish,\n ) -> Result<(), io::Error> {\n writeln!(self.0, \"\")?;\n writeln!(self.0, \"byte count:{}\", sink_finish.byte_count())?;\n if let Some(offset) = sink_finish.binary_byte_offset() {\n writeln!(self.0, \"binary offset:{}\", offset)?;\n }\n Ok(())\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":204,"symbol":"SearcherTester","kind":"type","lang":"rust","doc":"means there is no obviously direct way to ask that a specific code path be exercised. Thus, the purpose of this tester is to explicitly check as many code paths that make sense. The tester works by assuming you want to test all pertinent code paths. These can be trimmed down as necessary via the various builder methods.","code":"pub(crate) struct SearcherTester {\n haystack: String,\n pattern: String,\n filter: Option<::regex::Regex>,\n print_labels: bool,\n expected_no_line_number: Option,\n expected_with_line_number: Option,\n expected_slice_no_line_number: Option,\n expected_slice_with_line_number: Option,\n by_line: bool,\n multi_line: bool,\n invert_match: bool,\n line_number: bool,\n binary: BinaryDetection,\n auto_heap_limit: bool,\n after_context: usize,\n before_context: usize,\n passthru: bool,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":226,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new tester for testing searchers.","code":"pub(crate) fn new(haystack: &str, pattern: &str) -> SearcherTester {\n SearcherTester {\n haystack: haystack.to_string(),\n pattern: pattern.to_string(),\n filter: None,\n print_labels: false,\n expected_no_line_number: None,\n expected_with_line_number: None,\n expected_slice_no_line_number: None,\n expected_slice_with_line_number: None,\n by_line: true,\n multi_line: true,\n invert_match: false,\n line_number: true,\n binary: BinaryDetection::none(),\n auto_heap_limit: true,\n after_context: 0,\n before_context: 0,\n passthru: false,\n }\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":250,"symbol":"test","kind":"function","lang":"rust","doc":"Execute the test. If the test succeeds, then this returns successfully. If the test fails, then it panics with an informative message.","code":"pub(crate) fn test(&self) {\n // Check for configuration errors.\n if self.expected_no_line_number.is_none() {\n panic!(\"an 'expected' string with NO line numbers must be given\");\n }\n if self.line_number && self.expected_with_line_number.is_none() {\n panic!(\n \"an 'expected' string with line numbers must be given, \\\n or disable testing with line numbers\"\n );\n }\n\n let configs = self.configs();\n if configs.is_empty() {\n panic!(\"test configuration resulted in nothing being tested\");\n }\n if self.print_labels {\n for config in &configs {\n let labels = vec![\n format!(\"reader-{}\", config.label),\n format!(\"slice-{}\", config.label),\n ];\n for label in &labels {\n if self.include(label) {\n println!(\"{}\", label);\n } else {\n println!(\"{} (ignored)\", label);\n }\n }\n }\n }\n for config in &configs {\n let label = format!(\"re"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":305,"symbol":"filter","kind":"function","lang":"rust","doc":"By default, no filter is present. When a filter is set, only test configurations with a label matching the given pattern will be run. This is often useful when debugging tests, e.g., when you want to do printf debugging and only want one particular test configuration to execute.","code":"pub(crate) fn filter(&mut self, pattern: &str) -> &mut SearcherTester {\n self.filter = Some(::regex::Regex::new(pattern).unwrap());\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":316,"symbol":"print_labels","kind":"function","lang":"rust","doc":"When set, the labels for all test configurations are printed before executing any test. Note that in order to see these in tests that aren't failing, you'll want to use `cargo test -- --nocapture`.","code":"pub(crate) fn print_labels(&mut self, yes: bool) -> &mut SearcherTester {\n self.print_labels = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":322,"symbol":"expected_no_line_number","kind":"function","lang":"rust","doc":"Set the expected search results, without line numbers.","code":"pub(crate) fn expected_no_line_number(\n &mut self,\n exp: &str,\n ) -> &mut SearcherTester {\n self.expected_no_line_number = Some(exp.to_string());\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":331,"symbol":"expected_with_line_number","kind":"function","lang":"rust","doc":"Set the expected search results, with line numbers.","code":"pub(crate) fn expected_with_line_number(\n &mut self,\n exp: &str,\n ) -> &mut SearcherTester {\n self.expected_with_line_number = Some(exp.to_string());\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":342,"symbol":"expected_slice_no_line_number","kind":"function","lang":"rust","doc":"Set the expected search results, without line numbers, when performing a search on a slice. When not present, `expected_no_line_number` is used instead.","code":"pub(crate) fn expected_slice_no_line_number(\n &mut self,\n exp: &str,\n ) -> &mut SearcherTester {\n self.expected_slice_no_line_number = Some(exp.to_string());\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":354,"symbol":"expected_slice_with_line_number","kind":"function","lang":"rust","doc":"Set the expected search results, with line numbers, when performing a search on a slice. When not present, `expected_with_line_number` is used instead.","code":"pub(crate) fn expected_slice_with_line_number(\n &mut self,\n exp: &str,\n ) -> &mut SearcherTester {\n self.expected_slice_with_line_number = Some(exp.to_string());\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":367,"symbol":"line_number","kind":"function","lang":"rust","doc":"Whether to test search with line numbers or not. This is enabled by default. When enabled, the string that is expected when line numbers are present must be provided. Otherwise, the expected string isn't required.","code":"pub(crate) fn line_number(&mut self, yes: bool) -> &mut SearcherTester {\n self.line_number = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":375,"symbol":"by_line","kind":"function","lang":"rust","doc":"Whether to test search using the line-by-line searcher or not. By default, this is enabled.","code":"pub(crate) fn by_line(&mut self, yes: bool) -> &mut SearcherTester {\n self.by_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":384,"symbol":"multi_line","kind":"function","lang":"rust","doc":"Whether to test search using the multi line searcher or not. By default, this is enabled.","code":"pub(crate) fn multi_line(&mut self, yes: bool) -> &mut SearcherTester {\n self.multi_line = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":392,"symbol":"invert_match","kind":"function","lang":"rust","doc":"Whether to perform an inverted search or not. By default, this is disabled.","code":"pub(crate) fn invert_match(&mut self, yes: bool) -> &mut SearcherTester {\n self.invert_match = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":400,"symbol":"binary_detection","kind":"function","lang":"rust","doc":"Whether to enable binary detection on all searches. By default, this is disabled.","code":"pub(crate) fn binary_detection(\n &mut self,\n detection: BinaryDetection,\n ) -> &mut SearcherTester {\n self.binary = detection;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":417,"symbol":"auto_heap_limit","kind":"function","lang":"rust","doc":"limit to its minimal value for normal operation, which checks that everything works even at the extremes. However, in some cases, the heap limit can (expectedly) alter the output slightly. For example, it can impact the number of bytes searched when performing binary detection. For convenience, it can be useful to disable the automatic heap limit test.","code":"pub(crate) fn auto_heap_limit(\n &mut self,\n yes: bool,\n ) -> &mut SearcherTester {\n self.auto_heap_limit = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":428,"symbol":"after_context","kind":"function","lang":"rust","doc":"Set the number of lines to include in the \"after\" context. The default is `0`, which is equivalent to not printing any context.","code":"pub(crate) fn after_context(\n &mut self,\n lines: usize,\n ) -> &mut SearcherTester {\n self.after_context = lines;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":439,"symbol":"before_context","kind":"function","lang":"rust","doc":"Set the number of lines to include in the \"before\" context. The default is `0`, which is equivalent to not printing any context.","code":"pub(crate) fn before_context(\n &mut self,\n lines: usize,\n ) -> &mut SearcherTester {\n self.before_context = lines;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":454,"symbol":"passthru","kind":"function","lang":"rust","doc":"When passthru is enabled, it effectively treats all non-matching lines as contextual lines. In other words, enabling this is akin to requesting an unbounded number of before and after contextual lines. This is disabled by default.","code":"pub(crate) fn passthru(&mut self, yes: bool) -> &mut SearcherTester {\n self.passthru = yes;\n self\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":468,"symbol":"minimal_heap_limit","kind":"function","lang":"rust","doc":"its terminator), but if context settings are enabled, then this must include the sum of the longest N lines. Note that this must account for whether the test is using multi line search or not, since multi line search requires being able to fit the entire haystack into memory.","code":"fn minimal_heap_limit(&self, multi_line: bool) -> usize {\n if multi_line {\n 1 + self.haystack.len()\n } else if self.before_context == 0 && self.after_context == 0 {\n 1 + self.haystack.lines().map(|s| s.len()).max().unwrap_or(0)\n } else {\n let mut lens: Vec =\n self.haystack.lines().map(|s| s.len()).collect();\n lens.sort();\n lens.reverse();\n\n let context_count = if self.passthru {\n self.haystack.lines().count()\n } else {\n // Why do we add 2 here? Well, we need to add 1 in order to\n // have room to search at least one line. We add another\n // because the implementation will occasionally include\n // an additional line when handling the context. There's\n // no particularly good reason, other than keeping the\n // implementation simple.\n 2 + self.before_context + self.after_context\n };\n\n // We add 1 to each line since `str::lines` doesn't include the\n // line terminator.\n lens.into_iter()\n .take"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":505,"symbol":"include","kind":"function","lang":"rust","doc":"Returns true if and only if the given label should be included as part of executing `test`. Inclusion is determined by the filter specified. If no filter has been given, then this always returns `true`.","code":"fn include(&self, label: &str) -> bool {\n let re = match self.filter {\n None => return true,\n Some(ref re) => re,\n };\n re.is_match(label)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":516,"symbol":"configs","kind":"function","lang":"rust","doc":"Configs generates a set of all search configurations that should be tested. The configs generated are based on the configuration in this builder.","code":"fn configs(&self) -> Vec {\n let mut configs = vec![];\n\n let matcher = RegexMatcher::new(&self.pattern);\n let mut builder = SearcherBuilder::new();\n builder\n .line_number(false)\n .invert_match(self.invert_match)\n .binary_detection(self.binary.clone())\n .after_context(self.after_context)\n .before_context(self.before_context)\n .passthru(self.passthru);\n\n if self.by_line {\n let mut matcher = matcher.clone();\n let mut builder = builder.clone();\n\n let expected_reader =\n self.expected_no_line_number.as_ref().unwrap().to_string();\n let expected_slice = match self.expected_slice_no_line_number {\n None => expected_reader.clone(),\n Some(ref e) => e.to_string(),\n };\n configs.push(TesterConfig {\n label: \"byline-noterm-nonumber\".to_string(),\n expected_reader: expected_reader.clone(),\n expected_slice: expected_slice.clone(),\n builder: builder.clone(),\n matcher: matcher.clone(),\n });\n\n "} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":681,"symbol":"TesterConfig","kind":"type","lang":"rust","code":"struct TesterConfig {\n label: String,\n expected_reader: String,\n expected_slice: String,\n builder: SearcherBuilder,\n matcher: RegexMatcher,\n}"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":693,"symbol":"search_reader","kind":"function","lang":"rust","doc":"Execute a search using a reader. This exercises the incremental search strategy, where the entire contents of the corpus aren't necessarily in memory at once.","code":"fn search_reader(&self, haystack: &str) -> String {\n let mut sink = KitchenSink::new();\n let mut searcher = self.builder.build();\n let result = searcher.search_reader(\n &self.matcher,\n haystack.as_bytes(),\n &mut sink,\n );\n if let Err(err) = result {\n let label = format!(\"reader-{}\", self.label);\n panic!(\"error running '{}': {}\", label, err);\n }\n String::from_utf8(sink.as_bytes().to_vec()).unwrap()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":710,"symbol":"search_slice","kind":"function","lang":"rust","doc":"Execute a search using a slice. This exercises the search routines that have the entire contents of the corpus in memory at one time.","code":"fn search_slice(&self, haystack: &str) -> String {\n let mut sink = KitchenSink::new();\n let mut searcher = self.builder.build();\n let result = searcher.search_slice(\n &self.matcher,\n haystack.as_bytes(),\n &mut sink,\n );\n if let Err(err) = result {\n let label = format!(\"slice-{}\", self.label);\n panic!(\"error running '{}': {}\", label, err);\n }\n String::from_utf8(sink.as_bytes().to_vec()).unwrap()\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":730,"symbol":"m","kind":"function","lang":"rust","code":"fn m(start: usize, end: usize) -> Match {\n Match::new(start, end)\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":735,"symbol":"empty_line1","kind":"function","lang":"rust","code":"fn empty_line1() {\n let haystack = b\"\";\n let matcher = RegexMatcher::new(r\"^$\");\n\n assert_eq!(matcher.find_at(haystack, 0), Ok(Some(m(0, 0))));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":743,"symbol":"empty_line2","kind":"function","lang":"rust","code":"fn empty_line2() {\n let haystack = b\"\\n\";\n let matcher = RegexMatcher::new(r\"^$\");\n\n assert_eq!(matcher.find_at(haystack, 0), Ok(Some(m(0, 0))));\n assert_eq!(matcher.find_at(haystack, 1), Ok(Some(m(1, 1))));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":752,"symbol":"empty_line3","kind":"function","lang":"rust","code":"fn empty_line3() {\n let haystack = b\"\\n\\n\";\n let matcher = RegexMatcher::new(r\"^$\");\n\n assert_eq!(matcher.find_at(haystack, 0), Ok(Some(m(0, 0))));\n assert_eq!(matcher.find_at(haystack, 1), Ok(Some(m(1, 1))));\n assert_eq!(matcher.find_at(haystack, 2), Ok(Some(m(2, 2))));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":762,"symbol":"empty_line4","kind":"function","lang":"rust","code":"fn empty_line4() {\n let haystack = b\"a\\n\\nb\\n\";\n let matcher = RegexMatcher::new(r\"^$\");\n\n assert_eq!(matcher.find_at(haystack, 0), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 1), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 2), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 3), Ok(Some(m(5, 5))));\n assert_eq!(matcher.find_at(haystack, 4), Ok(Some(m(5, 5))));\n assert_eq!(matcher.find_at(haystack, 5), Ok(Some(m(5, 5))));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":775,"symbol":"empty_line5","kind":"function","lang":"rust","code":"fn empty_line5() {\n let haystack = b\"a\\n\\nb\\nc\";\n let matcher = RegexMatcher::new(r\"^$\");\n\n assert_eq!(matcher.find_at(haystack, 0), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 1), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 2), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 3), Ok(None));\n assert_eq!(matcher.find_at(haystack, 4), Ok(None));\n assert_eq!(matcher.find_at(haystack, 5), Ok(None));\n assert_eq!(matcher.find_at(haystack, 6), Ok(None));\n }"} {"repo":"ripgrep","file":"crates/searcher/src/testutil.rs","line":789,"symbol":"empty_line6","kind":"function","lang":"rust","code":"fn empty_line6() {\n let haystack = b\"a\\n\";\n let matcher = RegexMatcher::new(r\"^$\");\n\n assert_eq!(matcher.find_at(haystack, 0), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 1), Ok(Some(m(2, 2))));\n assert_eq!(matcher.find_at(haystack, 2), Ok(Some(m(2, 2))));\n }"} {"repo":"ripgrep","file":"pkg/brew/ripgrep-bin.rb","line":1,"symbol":"RipgrepBin","kind":"class","lang":"ruby","code":"class RipgrepBin < Formula\n version '15.0.0'\n desc \"Recursively search directories for a regex pattern.\"\n homepage \"https://github.com/BurntSushi/ripgrep\"\n\n if OS.mac?\n url \"https://github.com/BurntSushi/ripgrep/releases/download/#{version}/ripgrep-#{version}-x86_64-apple-darwin.tar.gz\"\n sha256 \"af7825fcc69a2afc7a7aea55fc9af90e26421d8f20fe59df32e233c0b8a231c1\"\n elsif OS.linux?\n url \"https://github.com/BurntSushi/ripgrep/releases/download/#{version}/ripgrep-#{version}-x86_64-unknown-linux-musl.tar.gz\"\n sha256 \"33e15bcf1624b25cdd2a55813a47a2f95dbe126268203e76aa6a585d1e7b149c\"\n end\n\n conflicts_with \"ripgrep\"\n\n def install\n bin.install \"rg\"\n man1.install \"doc/rg.1\"\n\n bash_completion.install \"complete/rg.bash\"\n zsh_completion.install \"complete/_rg\"\n end\nend"} {"repo":"ripgrep","file":"pkg/brew/ripgrep-bin.rb","line":16,"symbol":"install","kind":"method","lang":"ruby","code":"def install\n bin.install \"rg\"\n man1.install \"doc/rg.1\"\n\n bash_completion.install \"complete/rg.bash\"\n zsh_completion.install \"complete/_rg\"\n end"} {"repo":"ripgrep","file":"tests/json.rs","line":12,"symbol":"Message","kind":"type","lang":"rust","code":"enum Message {\n Begin(Begin),\n End(End),\n Match(Match),\n Context(Context),\n Summary(Summary),\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":21,"symbol":"unwrap_begin","kind":"function","lang":"rust","code":"fn unwrap_begin(&self) -> Begin {\n match *self {\n Message::Begin(ref x) => x.clone(),\n ref x => panic!(\"expected Message::Begin but got {x:?}\"),\n }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":28,"symbol":"unwrap_end","kind":"function","lang":"rust","code":"fn unwrap_end(&self) -> End {\n match *self {\n Message::End(ref x) => x.clone(),\n ref x => panic!(\"expected Message::End but got {x:?}\"),\n }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":35,"symbol":"unwrap_match","kind":"function","lang":"rust","code":"fn unwrap_match(&self) -> Match {\n match *self {\n Message::Match(ref x) => x.clone(),\n ref x => panic!(\"expected Message::Match but got {x:?}\"),\n }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":42,"symbol":"unwrap_context","kind":"function","lang":"rust","code":"fn unwrap_context(&self) -> Context {\n match *self {\n Message::Context(ref x) => x.clone(),\n ref x => panic!(\"expected Message::Context but got {x:?}\"),\n }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":49,"symbol":"unwrap_summary","kind":"function","lang":"rust","code":"fn unwrap_summary(&self) -> Summary {\n match *self {\n Message::Summary(ref x) => x.clone(),\n ref x => panic!(\"expected Message::Summary but got {x:?}\"),\n }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":59,"symbol":"Begin","kind":"type","lang":"rust","code":"struct Begin {\n path: Option,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":65,"symbol":"End","kind":"type","lang":"rust","code":"struct End {\n path: Option,\n binary_offset: Option,\n stats: Stats,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":73,"symbol":"Summary","kind":"type","lang":"rust","code":"struct Summary {\n elapsed_total: Duration,\n stats: Stats,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":80,"symbol":"Match","kind":"type","lang":"rust","code":"struct Match {\n path: Option,\n lines: Data,\n line_number: Option,\n absolute_offset: u64,\n submatches: Vec,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":90,"symbol":"Context","kind":"type","lang":"rust","code":"struct Context {\n path: Option,\n lines: Data,\n line_number: Option,\n absolute_offset: u64,\n submatches: Vec,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":100,"symbol":"SubMatch","kind":"type","lang":"rust","code":"struct SubMatch {\n #[serde(rename = \"match\")]\n m: Data,\n replacement: Option,\n start: usize,\n end: usize,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":110,"symbol":"Data","kind":"type","lang":"rust","code":"enum Data {\n Text { text: String },\n // This variant is used when the data isn't valid UTF-8. The bytes are\n // base64 encoded, so using a String here is OK.\n Bytes { bytes: String },\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":118,"symbol":"text","kind":"function","lang":"rust","code":"fn text(s: &str) -> Data {\n Data::Text { text: s.to_string() }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":121,"symbol":"bytes","kind":"function","lang":"rust","code":"fn bytes(s: &str) -> Data {\n Data::Bytes { bytes: s.to_string() }\n }"} {"repo":"ripgrep","file":"tests/json.rs","line":128,"symbol":"Stats","kind":"type","lang":"rust","code":"struct Stats {\n elapsed: Duration,\n searches: u64,\n searches_with_match: u64,\n bytes_searched: u64,\n bytes_printed: u64,\n matched_lines: u64,\n matches: u64,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":140,"symbol":"Duration","kind":"type","lang":"rust","code":"struct Duration {\n #[serde(flatten)]\n duration: time::Duration,\n human: String,\n}"} {"repo":"ripgrep","file":"tests/json.rs","line":148,"symbol":"json_decode","kind":"function","lang":"rust","doc":"Decode JSON Lines into a Vec. If there was an error decoding, this function panics.","code":"fn json_decode(jsonlines: &str) -> Vec {\n json::Deserializer::from_str(jsonlines)\n .into_iter()\n .collect::, _>>()\n .unwrap()\n}"} {"repo":"ripgrep","file":"tests/misc.rs","line":1155,"symbol":"sort_setup","kind":"function","lang":"rust","doc":"├── b # 4 └── dir # 2 ├── c # 3 └── d # 5 This order is important when sorting them by system time-stamps.","code":"fn sort_setup(dir: Dir) {\n use std::{thread::sleep, time::Duration};\n // As reported in https://github.com/BurntSushi/ripgrep/issues/3071\n // this test fails if sufficient delay is not given on Windows/Aarch64.\n let delay = if cfg!(all(windows, target_arch = \"aarch64\")) {\n Duration::from_millis(1000)\n } else {\n Duration::from_millis(100)\n };\n let sub_dir = dir.path().join(\"dir\");\n dir.create(\"a\", \"test\");\n sleep(delay);\n dir.create_dir(&sub_dir);\n sleep(delay);\n dir.create(sub_dir.join(\"c\"), \"test\");\n sleep(delay);\n dir.create(\"b\", \"test\");\n sleep(delay);\n dir.create(sub_dir.join(\"d\"), \"test\");\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":22,"symbol":"setup","kind":"function","lang":"rust","doc":"Setup an empty work directory and return a command pointing to the ripgrep executable whose CWD is set to the work directory. The name given will be used to create the directory. Generally, it should correspond to the test name.","code":"pub fn setup(test_name: &str) -> (Dir, TestCommand) {\n let dir = Dir::new(test_name);\n let cmd = dir.command();\n (dir, cmd)\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":29,"symbol":"setup_pcre2","kind":"function","lang":"rust","doc":"Like `setup`, but uses PCRE2 as the underlying regex engine.","code":"pub fn setup_pcre2(test_name: &str) -> (Dir, TestCommand) {\n let mut dir = Dir::new(test_name);\n dir.pcre2(true);\n let cmd = dir.command();\n (dir, cmd)\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":39,"symbol":"sort_lines","kind":"function","lang":"rust","doc":"Break the given string into lines, sort them and then join them back together. This is useful for testing output from ripgrep that may not always be in the same order.","code":"pub fn sort_lines(lines: &str) -> String {\n let mut lines: Vec<&str> = lines.trim().lines().collect();\n lines.sort();\n format!(\"{}\\n\", lines.join(\"\\n\"))\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":47,"symbol":"cmd_exists","kind":"function","lang":"rust","doc":"Returns true if and only if the given program can be successfully executed with a `--help` flag.","code":"pub fn cmd_exists(program: &str) -> bool {\n match Command::new(program).arg(\"--help\").output() {\n Ok(output) => output.status.success(),\n Err(_) => false,\n }\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":58,"symbol":"Dir","kind":"type","lang":"rust","doc":"Dir represents a directory in which tests should be run. Directories are created from a global atomic counter to avoid duplicates.","code":"pub struct Dir {\n /// The directory in which this test executable is running.\n root: PathBuf,\n /// The directory in which the test should run. If a test needs to create\n /// files, they should go in here. This directory is also used as the CWD\n /// for any processes created by the test.\n dir: PathBuf,\n /// Set to true when the test should use PCRE2 as the regex engine.\n pcre2: bool,\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":73,"symbol":"new","kind":"function","lang":"rust","doc":"Create a new test working directory with the given name. The name does not need to be distinct for each invocation, but should correspond to a logical grouping of tests.","code":"pub fn new(name: &str) -> Dir {\n let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);\n let root = env::current_exe()\n .unwrap()\n .parent()\n .expect(\"executable's directory\")\n .to_path_buf();\n let dir =\n env::temp_dir().join(TEST_DIR).join(name).join(&format!(\"{id}\"));\n if dir.exists() {\n nice_err(&dir, fs::remove_dir_all(&dir));\n }\n nice_err(&dir, repeat(|| fs::create_dir_all(&dir)));\n Dir { root, dir, pcre2: false }\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":90,"symbol":"pcre2","kind":"function","lang":"rust","doc":"Use PCRE2 for this test.","code":"pub fn pcre2(&mut self, yes: bool) {\n self.pcre2 = yes;\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":96,"symbol":"is_pcre2","kind":"function","lang":"rust","doc":"Returns true if and only if this test is configured to use PCRE2 as the regex engine.","code":"pub fn is_pcre2(&self) -> bool {\n self.pcre2\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":102,"symbol":"create","kind":"function","lang":"rust","doc":"Create a new file with the given name and contents in this directory, or panic on error.","code":"pub fn create>(&self, name: P, contents: &str) {\n self.create_bytes(name, contents.as_bytes());\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":109,"symbol":"try_create","kind":"function","lang":"rust","doc":"Try to create a new file with the given name and contents in this directory.","code":"pub fn try_create>(\n &self,\n name: P,\n contents: &str,\n ) -> io::Result<()> {\n let path = self.dir.join(name);\n self.try_create_bytes(path, contents.as_bytes())\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":119,"symbol":"create_size","kind":"function","lang":"rust","doc":"Create a new file with the given name and size.","code":"pub fn create_size>(&self, name: P, filesize: u64) {\n let path = self.dir.join(name);\n let file = nice_err(&path, File::create(&path));\n nice_err(&path, file.set_len(filesize));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":127,"symbol":"create_bytes","kind":"function","lang":"rust","doc":"Create a new file with the given name and contents in this directory, or panic on error.","code":"pub fn create_bytes>(&self, name: P, contents: &[u8]) {\n let path = self.dir.join(&name);\n nice_err(&path, self.try_create_bytes(name, contents));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":134,"symbol":"try_create_bytes","kind":"function","lang":"rust","doc":"Try to create a new file with the given name and contents in this directory.","code":"pub fn try_create_bytes>(\n &self,\n name: P,\n contents: &[u8],\n ) -> io::Result<()> {\n let path = self.dir.join(name);\n let mut file = File::create(path)?;\n file.write_all(contents)?;\n file.flush()\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":146,"symbol":"remove","kind":"function","lang":"rust","doc":"Remove a file with the given name from this directory.","code":"pub fn remove>(&self, name: P) {\n let path = self.dir.join(name);\n nice_err(&path, fs::remove_file(&path));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":153,"symbol":"create_dir","kind":"function","lang":"rust","doc":"Create a new directory with the given path (and any directories above it) inside this directory.","code":"pub fn create_dir>(&self, path: P) {\n let path = self.dir.join(path);\n nice_err(&path, repeat(|| fs::create_dir_all(&path)));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":167,"symbol":"command","kind":"function","lang":"rust","doc":"This also: * Unsets the `RIPGREP_CONFIG_PATH` environment variable. * Sets the `--path-separator` to `/` so that paths have the same output on all systems. Tests that need to check `--path-separator` itself can simply pass it again to override it.","code":"pub fn command(&self) -> TestCommand {\n let mut cmd = self.bin();\n cmd.env_remove(\"RIPGREP_CONFIG_PATH\");\n cmd.current_dir(&self.dir);\n cmd.arg(\"--path-separator\").arg(\"/\");\n if self.is_pcre2() {\n cmd.arg(\"--pcre2\");\n }\n TestCommand { dir: self.clone(), cmd }\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":179,"symbol":"bin","kind":"function","lang":"rust","doc":"Returns the path to the ripgrep executable.","code":"pub fn bin(&self) -> process::Command {\n let rg = std::env::var_os(\"CARGO_BIN_EXE_rg\")\n .map(PathBuf::from)\n .unwrap_or_else(|| {\n self.root.join(format!(\"../rg{}\", env::consts::EXE_SUFFIX))\n });\n match cross_runner() {\n None => process::Command::new(rg),\n Some(runner) => {\n let mut cmd = process::Command::new(runner);\n cmd.arg(rg);\n cmd\n }\n }\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":196,"symbol":"path","kind":"function","lang":"rust","doc":"Returns the path to this directory.","code":"pub fn path(&self) -> &Path {\n &self.dir\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":203,"symbol":"link_dir","kind":"function","lang":"rust","doc":"Creates a directory symlink to the src with the given target name in this directory.","code":"pub fn link_dir, T: AsRef>(&self, src: S, target: T) {\n use std::os::unix::fs::symlink;\n let src = self.dir.join(src);\n let target = self.dir.join(target);\n let _ = fs::remove_file(&target);\n nice_err(&target, symlink(&src, &target));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":214,"symbol":"link_dir","kind":"function","lang":"rust","doc":"Creates a directory symlink to the src with the given target name in this directory.","code":"pub fn link_dir, T: AsRef>(&self, src: S, target: T) {\n use std::os::windows::fs::symlink_dir;\n let src = self.dir.join(src);\n let target = self.dir.join(target);\n let _ = fs::remove_dir(&target);\n nice_err(&target, symlink_dir(&src, &target));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":225,"symbol":"link_file","kind":"function","lang":"rust","doc":"Creates a file symlink to the src with the given target name in this directory.","code":"pub fn link_file, T: AsRef>(\n &self,\n src: S,\n target: T,\n ) {\n self.link_dir(src, target);\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":237,"symbol":"link_file","kind":"function","lang":"rust","doc":"Creates a file symlink to the src with the given target name in this directory.","code":"pub fn link_file, T: AsRef>(\n &self,\n src: S,\n target: T,\n ) {\n use std::os::windows::fs::symlink_file;\n let src = self.dir.join(src);\n let target = self.dir.join(target);\n let _ = fs::remove_file(&target);\n nice_err(&target, symlink_file(&src, &target));\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":252,"symbol":"TestCommand","kind":"type","lang":"rust","doc":"A simple wrapper around a process::Command with some conveniences.","code":"pub struct TestCommand {\n /// The dir used to launched this command.\n dir: Dir,\n /// The actual command we use to control the process.\n cmd: Command,\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":261,"symbol":"cmd","kind":"function","lang":"rust","doc":"Returns a mutable reference to the underlying command.","code":"pub fn cmd(&mut self) -> &mut Command {\n &mut self.cmd\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":266,"symbol":"arg","kind":"function","lang":"rust","doc":"Add an argument to pass to the command.","code":"pub fn arg>(&mut self, arg: A) -> &mut TestCommand {\n self.cmd.arg(arg);\n self\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":272,"symbol":"args","kind":"function","lang":"rust","doc":"Add any number of arguments to the command.","code":"pub fn args(&mut self, args: I) -> &mut TestCommand\n where\n I: IntoIterator,\n A: AsRef,\n {\n self.cmd.args(args);\n self\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":282,"symbol":"env","kind":"function","lang":"rust","doc":"Set an environment variable for this command.","code":"pub fn env(\n &mut self,\n key: impl AsRef,\n val: impl AsRef,\n ) -> &mut TestCommand {\n self.cmd.env(key, val);\n self\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":299,"symbol":"current_dir","kind":"function","lang":"rust","doc":"The path given is interpreted relative to the directory that this command was created for. Note that this does not need to be called normally, since the creation of this TestCommand causes its working directory to be set to the test's directory automatically.","code":"pub fn current_dir>(&mut self, dir: P) -> &mut TestCommand {\n self.cmd.current_dir(self.dir.path().join(dir));\n self\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":305,"symbol":"stdout","kind":"function","lang":"rust","doc":"Runs and captures the stdout of the given command.","code":"pub fn stdout(&mut self) -> String {\n let o = self.output();\n String::from_utf8_lossy(&o.stdout).into_owned()\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":311,"symbol":"pipe","kind":"function","lang":"rust","doc":"Pipe `input` to a command, and collect the output.","code":"pub fn pipe(&mut self, input: &[u8]) -> String {\n self.cmd.stdin(process::Stdio::piped());\n self.cmd.stdout(process::Stdio::piped());\n self.cmd.stderr(process::Stdio::piped());\n\n let mut child = self.cmd.spawn().unwrap();\n\n // Pipe input to child process using a separate thread to avoid\n // risk of deadlock between parent and child process.\n let mut stdin = child.stdin.take().expect(\"expected standard input\");\n let input = input.to_owned();\n let worker = thread::spawn(move || stdin.write_all(&input));\n\n let output = self.expect_success(child.wait_with_output().unwrap());\n worker.join().unwrap().unwrap();\n\n String::from_utf8_lossy(&output.stdout).into_owned()\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":331,"symbol":"output","kind":"function","lang":"rust","doc":"Gets the output of a command. If the command failed, then this panics.","code":"pub fn output(&mut self) -> process::Output {\n let output = self.raw_output();\n self.expect_success(output)\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":338,"symbol":"raw_output","kind":"function","lang":"rust","doc":"Gets the raw output of a command after filtering nonsense like jemalloc error messages from stderr.","code":"pub fn raw_output(&mut self) -> process::Output {\n let mut output = self.cmd.output().unwrap();\n output.stderr = strip_jemalloc_nonsense(&output.stderr);\n output\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":345,"symbol":"assert_err","kind":"function","lang":"rust","doc":"Runs the command and asserts that it resulted in an error exit code.","code":"pub fn assert_err(&mut self) {\n let o = self.raw_output();\n if o.status.success() {\n panic!(\n \"\\n\\n===== {:?} =====\\n\\\n command succeeded but expected failure!\\\n \\n\\ncwd: {}\\\n \\n\\ndir list: {:?}\\\n \\n\\nstatus: {}\\\n \\n\\nstdout: {}\\n\\nstderr: {}\\\n \\n\\n=====\\n\",\n self.cmd,\n self.dir.dir.display(),\n dir_list(&self.dir.dir),\n o.status,\n String::from_utf8_lossy(&o.stdout),\n String::from_utf8_lossy(&o.stderr)\n );\n }\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":368,"symbol":"assert_exit_code","kind":"function","lang":"rust","doc":"Runs the command and asserts that its exit code matches expected exit code.","code":"pub fn assert_exit_code(&mut self, expected_code: i32) {\n let code = self.cmd.output().unwrap().status.code().unwrap();\n assert_eq!(\n expected_code,\n code,\n \"\\n\\n===== {:?} =====\\n\\\n expected exit code did not match\\\n \\n\\ncwd: {}\\\n \\n\\ndir list: {:?}\\\n \\n\\nexpected: {}\\\n \\n\\nfound: {}\\\n \\n\\n=====\\n\",\n self.cmd,\n self.dir.dir.display(),\n dir_list(&self.dir.dir),\n expected_code,\n code\n );\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":389,"symbol":"assert_non_empty_stderr","kind":"function","lang":"rust","doc":"Runs the command and asserts that something was printed to stderr.","code":"pub fn assert_non_empty_stderr(&mut self) {\n let o = self.cmd.output().unwrap();\n if o.status.success() || o.stderr.is_empty() {\n panic!(\n \"\\n\\n===== {:?} =====\\n\\\n command succeeded but expected failure!\\\n \\n\\ncwd: {}\\\n \\n\\ndir list: {:?}\\\n \\n\\nstatus: {}\\\n \\n\\nstdout: {}\\n\\nstderr: {}\\\n \\n\\n=====\\n\",\n self.cmd,\n self.dir.dir.display(),\n dir_list(&self.dir.dir),\n o.status,\n String::from_utf8_lossy(&o.stdout),\n String::from_utf8_lossy(&o.stderr)\n );\n }\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":410,"symbol":"expect_success","kind":"function","lang":"rust","code":"fn expect_success(&self, o: process::Output) -> process::Output {\n if !o.status.success() {\n let suggest = if o.stderr.is_empty() {\n \"\\n\\nDid your search end up with no results?\".to_string()\n } else {\n \"\".to_string()\n };\n\n panic!(\n \"\\n\\n==========\\n\\\n command failed but expected success!\\\n {}\\\n \\n\\ncommand: {:?}\\\n \\n\\ncwd: {}\\\n \\n\\ndir list: {:?}\\\n \\n\\nstatus: {}\\\n \\n\\nstdout: {}\\\n \\n\\nstderr: {}\\\n \\n\\n==========\\n\",\n suggest,\n self.cmd,\n self.dir.dir.display(),\n dir_list(&self.dir.dir),\n o.status,\n String::from_utf8_lossy(&o.stdout),\n String::from_utf8_lossy(&o.stderr)\n );\n }\n o\n }"} {"repo":"ripgrep","file":"tests/util.rs","line":442,"symbol":"nice_err","kind":"function","lang":"rust","code":"fn nice_err(path: &Path, res: Result) -> T {\n match res {\n Ok(t) => t,\n Err(err) => panic!(\"{}: {:?}\", path.display(), err),\n }\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":449,"symbol":"repeat","kind":"function","lang":"rust","code":"fn repeat io::Result<()>>(mut f: F) -> io::Result<()> {\n let mut last_err = None;\n for _ in 0..10 {\n if let Err(err) = f() {\n last_err = Some(err);\n thread::sleep(Duration::from_millis(500));\n } else {\n return Ok(());\n }\n }\n Err(last_err.unwrap())\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":465,"symbol":"dir_list","kind":"function","lang":"rust","doc":"Return a recursive listing of all files and directories in the given directory. This is useful for debugging transient and odd failures in integration tests.","code":"fn dir_list>(dir: P) -> Vec {\n walkdir::WalkDir::new(dir)\n .follow_links(true)\n .into_iter()\n .map(|result| result.unwrap().path().to_string_lossy().into_owned())\n .collect()\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":492,"symbol":"cross_runner","kind":"function","lang":"rust","doc":"case. Perfect, so just get the current target architecture and append it to `qemu-`. Wrong. Cross (or qemu or whoever) uses `qemu-ppc64` for `powerpc64`, so we can't just use the target architecture as Rust knows it verbatim. So... we just manually handle these cases. So fucking fun.","code":"fn cross_runner() -> Option {\n let runner = std::env::var(\"CROSS_RUNNER\").ok()?;\n if runner.is_empty() || runner == \"empty\" {\n return None;\n }\n if cfg!(target_arch = \"powerpc64\") {\n Some(\"qemu-ppc64\".to_string())\n } else if cfg!(target_arch = \"x86\") {\n Some(\"i386\".to_string())\n } else {\n // Make a guess... Sigh.\n Some(format!(\"qemu-{}\", std::env::consts::ARCH))\n }\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":512,"symbol":"is_cross","kind":"function","lang":"rust","doc":"Returns true if the test setup believes Cross is running and `qemu` is needed to run ripgrep. This is useful because it has been difficult to get some tests to pass under Cross.","code":"pub fn is_cross() -> bool {\n std::env::var(\"CROSS_RUNNER\").ok().map_or(false, |v| !v.is_empty())\n}"} {"repo":"ripgrep","file":"tests/util.rs","line":523,"symbol":"strip_jemalloc_nonsense","kind":"function","lang":"rust","doc":"In theory this only happens under qemu, which is where our tests run under `cross`. But is messes with our tests, because... they don't expect the allocator to fucking write to stderr. I mean, what the fuck? Who prints a warning message with absolutely no instruction for what to do with it or how to disable it. Absolutely fucking bonkers.","code":"fn strip_jemalloc_nonsense(data: &[u8]) -> Vec {\n let lines = data\n .lines_with_terminator()\n .filter(|line| !line.starts_with_str(\":\"));\n bstr::concat(lines)\n}"}