Metadata-Version: 2.4
Name: grepsr-cli
Version: 0.10.39
Summary: A Cli tool for Grepsr Developers
Home-page: https://bitbucket.org/grepsr/grepsr-cli/
Author: grepsr
Author-email: dev@grepsr.com
License: unlicensed
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: cement>=3.0.4
Requires-Dist: Jinja2>=2.11.3
Requires-Dist: PyYAML==6.0.1
Requires-Dist: colorlog>=4.8.0
Requires-Dist: semver>=2.13.0
Requires-Dist: terminaltables>=3.1.0
Requires-Dist: requests>=2.25.1
Requires-Dist: boto3<2.0.0,>=1.9.0
Dynamic: author
Dynamic: author-email
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license
Dynamic: license-file
Dynamic: requires-dist
Dynamic: summary

# A Cli tool for Grepsr Developers

## Installation
```
$ pip install grepsr-cli
```


## Usage

### Using help

```bash
gcli --help
```

### Using help for a specific command

```bash
gcli create --help
```

### Tab completion

```bash
gcli generate tab-completion
```

Installs completion for bash, zsh or fish (detected from `$SHELL`, or pass
`--shell bash|zsh|fish`). New shells pick it up automatically; to also turn it on
in the shell you are in, do it in one step instead:

```bash
source <(gcli generate tab-completion --print)   # bash, zsh
gcli generate tab-completion --print | source    # fish
```

Completes subcommands, flag names, and crawler names read live from the `paths`
in `~/.grepsr/config.yml` — no need to re-run it when you clone a new crawler.

```bash
gcli crawler test -s amaz<TAB>            # every crawler starting with "amaz"
gcli crawler test -t node -s <TAB>        # only crawlers under node.paths
```

### Creating crawler
```bash
gcli crawler create --init
```
This will take you to the interactive mode, where you can choose which crawler to create (PHP/JavaScript/Typescript)

![Create crawler interactive mode](docs/images/create_crawler_interactive_mode.png)

Every answer can also be passed as a flag, which is how scripts and AI agents (no terminal
to answer prompts) create crawlers:
```bash
gcli crawler create --lang ts --client acme --site https://acme.com/products --category products \
  --jira DEL-1234 --pid 5678 --columns "name,price,url" --packages crawler-utils --yes --json
```
- `--lang`: `php`, `js`, `ts`, `js-es6` or `ts-base` (base class; needs only `--client`)
- `--packages`: `crawler-utils` (default), `sdk`, `none`, or a comma separated list
- `--dry-run` prints the generated plugin name and path without creating anything
- `--json` prints one JSON object on stdout (`plugin_name`, `path`, `entry_file`, `files`, ...); logs go to stderr
- without a terminal nothing is asked: missing required flags are listed in one error (exit code 2).
  Exit code 17 means the plugin name is taken, 3 that the files were created but `npm install` failed.
- flags given with `--init` in a terminal are used as is; only the rest is asked.

### Running crawler.
```bash
gcli crawler test -s amazon_com
```


### Watching a crawler run (node crawlers)
```bash
gcli crawler test -s amazon_com --observe              # a live dashboard in the terminal
gcli crawler test -s amazon_com --observe --browser    # and the browser report right away
gcli crawler test -s amazon_com --observe --no-tui     # plain output; the browser report opens instead
```
The dashboard shows the crawler's log, every request it made (with a curl to replay
it), memory over time and what holds it, proxies, and how busy its work queues are.
Each run also gets a report you can open in a browser, and a summary when it ends.
It works on linux and mac with any docker setup (Docker Desktop, colima, OrbStack ...).
It uses node 20 or newer on your machine, or runs in docker (in the node sdk image)
when there is none, and works with any sdk image; nothing in `config.yml` changes. Runs are kept in `~/.grepsr/tmp/observe/` for 21 days.
More in [the observatory's README](grepsrcli/observatory/README.md).

### Attaching a debugger (mac/windows)

On linux the crawler container shares your machine's network, so the node
inspector is on `localhost:9229` and nothing else is needed. On mac and windows
docker runs in a VM, so gcli uses bridge networking instead and:

- publishes the node inspector on `localhost:9229`, so a vscode `attach`
  configuration connects as it does on linux;
- rewrites `127.0.0.1` / `localhost` in your `config.yml` env values to
  `host.docker.internal`, so `MAESTRO_HOST`, the `*_LOCAL_WSS` endpoints and any
  proxy still reach the services running on your machine.

To expose more container ports, list them under the crawler type in
`~/.grepsr/config.yml`:

```yaml
node:
    publish_ports:
        - 9229          # node inspector, the default when the key is absent
        - 3000          # same port on both sides
        - "8080:80"     # host:container
```

A port already in use is skipped with a warning rather than failing the run, so a
second crawler still runs (just without a debugger). Ports the container needs to
*reach* on your machine need no entry here.

Do not put `--inspect` in your `config.yml` `NODE_OPTIONS`: it reaches every node
process, so `npm` opens the inspector first and the crawler it spawns then fails
with "address already in use", leaving you attached to npm. gcli drops the flag
with a warning and pins the host with `--inspect-port` instead, which only the
process that actually asks for an inspector picks up.


### Running crawler with a parameter.
```bash
gcli crawler test -s amazon_com -p '{"urls":["https://amazon.com/VVUH4HJ","https://amazon.com/FV4434"]}'
```

### if JSON is complex, use a file instead
```
# contents of /tmp/amazon_params.json
{"urls": ["https://amazon.com/VV%20UH4HJ"], "strip": ["'", "\"", "\\"]}

gcli crawler test -s amazon_com --params-file '/tmp/amazon_params.json'
```

#### Hacks Used.
> If the json parameter has a space, it might break parameter parsing.
> If the json parameter has a dash `-` and any character after it has a space, it will break parameter parsing.
Cause: no double quoting around $@ in `run_service.php:5:49` [here](https://bitbucket.org/grepsr/vortex-backend/src/09c263fb0bb538003db01e1d6742a43ae6ebc61a/deploy/vortex-backend/scripts/run_service.sh#lines-5)
> This is fixed hackily by replacing string with its unicode \u0020 sequence. This works beacause $@ does not split on \u0020.

### Installing NodeJS package in a crawler

```bash
gcli crawler package-install -p @vortex-ts-sdk/http-crawler -t node -s grepsr_api_oxylab_com_report
```
```bash
gcli crawler package-install -p typescript -t node -s grepsr_api_oxylab_com_report
```

### Updating a crawler's Vortex packages

Bumps every `@vortex-ts-registry/*` and `@vortex-ts-sdk/*` dependency to its latest version.
Third party packages are left alone. You get an old → new preview to confirm first, and the
crawler is compiled afterwards to check the new versions still build.

```bash
gcli crawler package-update -s grepsr_api_oxylab_com_report
```

Use `--dry-run` to see what would change without touching anything, `-p` to limit it to
specific packages, and `-y` to skip the prompt.

```bash
gcli crawler package-update -s grepsr_api_oxylab_com_report --dry-run
gcli crawler package-update -s grepsr_api_oxylab_com_report -p @vortex-ts-sdk/http-crawler -y
```

`gcli crawler test` reminds you when a crawler has fallen behind:

```
WARNING: 3 vortex packages out of date:
         @vortex-ts-registry/crawler-utils   3.4.8 -> 5.3.9  (2 major versions)
         @vortex-ts-sdk/cache-handler        0.9.0 -> 0.13.1  (crosses 4 breaking 0.x releases)
         @vortex-ts-sdk/http-crawler        0.11.0 -> 0.14.1  (crosses 3 breaking 0.x releases)
       Run `gcli crawler package-update -s aakash_test_kathmandupost_com` to update.
```

It answers from a cache, so it costs a fraction of a millisecond and never delays the crawler.
Once a day the run pauses up front to refresh that cache from the registry, and says so while it
does. Running `package-update` refreshes it too, and CI never pauses for it.

### Running Browser Automation

To run browser automation locally using `gcli`:

1. **Pull the browser image** from AWS ECR:
   ```bash
   gcli browser pull <browser_name>
   ```

2. **Run the browser container**:
   ```bash
   gcli browser run <browser_name>
   ```

3. **View the browser VNC stream using noVNC**:
   To view the browser's graphical output, start the noVNC container mapping to the host's VNC port (`5900`):
   ```bash
   docker run \
     --add-host=host.docker.internal:host-gateway \
     -p 127.0.0.1:6080:6080 \
     gotget/novnc \
     --vnc host.docker.internal:5900
   ```
   Once running, open `http://127.0.0.1:6080/vnc.html` in your web browser to interact with the containerized browser.

#### Running two browsers at once

Every browser container publishes its WebSocket port (`WS_PORT`) and VNC port (`5900`) on your machine,
so a second browser needs different host ports. Set them per browser in `~/.grepsr/config.yml`:

```yaml
browser-automation:
  env:
    WS_PORT: 8088
    # ...
  camoufox:
    image_uri: <camoufox image>
  cloak:
    image_uri: <cloak image>
    port: 8089       # host port for its WebSocket, instead of WS_PORT
    vnc_port: 5901   # host port for its VNC, instead of 5900
```

Then `gcli browser run camoufox` and `gcli browser run cloak` run side by side. The same can be done
for one run with `--port` and `--vnc-port`, which win over the config. Point a second noVNC at the new port
(`--vnc host.docker.internal:5901`, published on another port such as `-p 127.0.0.1:6081:6080`).

#### Connecting a crawler to the browsers

`gcli crawler test` hands each browser in `browser-automation` to a node crawler as an env var, so the
`*_LOCAL_WSS` urls no longer need to be written into `node.env`. `wss_env` names the variable the crawler
reads, and a browser without one is not passed:

```yaml
  camoufox:
    image_uri: <camoufox image>
    port: 8089
    wss_env: CAMO_LOCAL_WSS
```

The url is built from the shared `env` and the browser's `port`:

```
CAMO_LOCAL_WSS=ws://127.0.0.1:8089/sessions/<REPORT_ID>-<HISTORY_ID>-<SESSION_ID>/ws
```

A url you still set in `node.env` wins over the generated one, so existing configs keep working.


### inject custom command.
Say, for example, you wanted to inject a PHP function so that it could be called from inside your service code when testing locally.
Note: All these files should only be created inside `~/.grepsr/tmp`. Creating it outside will not work.

1. Create a file called `inject.php` inside `~/.grepsr/tmp/`
2. Implement your function inside `~/.grepsr/tmp/inject.php`
```php
function addRowLocal($arr) {
    ...
    ...
}
```
3. Create a file called `inject.sh` inside `~/.grepsr/tmp/`
4. inside inject.sh add:
```
alias php='php -d auto_prepend_file=/tmp/inject.php'
```
Note: the file location is `/tmp/inject.php` instead of `~/.grepsr/tmp/inject.php`.
This is because, the local path `~/.grepsr/tmp` gets mapped to `/tmp` in the docker container.
And `inject.sh` runs inside docker, instead of the local filesystem.
5. Add an entry in `~/.grepst/config.yml` like so:
```yml
    php:
        ...
        sdk_image: ...
        pre_entry_run_file: inject.sh      # relative and limited to the tmp/ dir
```
6. Now you can use `addRowLocal()` in your any of your files.
```php
public function main($params) {
    ...
    $arr = $this->dataSet->getEmptyRow();
    addRowLocal($arr); // won't throw error
    ...
}
```
## Would you like to contribute to grepsr-cli?
> Be sure to uninstall gcli first, with
`pip uninstall grepsr-cli` make changes, test and push.

```bash
git clone git@bitbucket.org:zznixt07/gcli.git grepsrcli
cd grepsrcli
pip install -e .
```

## Features Added
- drop stash after pushed successully. Before this, all stashes were always kept.
- run a custom shell file before running your crawler. This allows possiblity like always injecting a php function in all your crawlers.
- auto add `Dependencies: ...` that your crawler class extends (dependecies that are not extended by crawler classes but used elsewhere is upcoming)
- Show modified files in the working tree that would be lost on git pull conflict, including the author name and date/time of the last local commit.
- Scan PHP and Node (JS/TS) plugins for unexpected termination statements (e.g. `die()`, `exit()`) and merge conflict markers (`<<<<<<< HEAD`), prompting user before deployment.
- Warn Node/TS crawler developers if `src/` directory has changes but the compiled `lib/` directory does not.
- Expose CLI configuration globally so it can be read from anywhere, and print the `docker run` command when verbose mode is enabled.
- Plugin names are checked for global uniqueness across every repo and language: `create` refuses a name that already exists anywhere, `test`/`deploy` warn when one resolves to more than one location.
- On a duplicate plugin name, the copy closest to the current working directory is used instead of whichever repo happens to be configured first.


# TODO:
- ~~Experiment with git rebase on deploy fail. `git rebase origin/master --autostash && git push`~~
- ~~Handle Prioritization of same plugin name across multiple repo more deterministically. (maybe prioritize cwd path?)~~
- ~~node only run crawler if npm install is successfull. (add && between npm install and npm start)~~
- run `tsc` before deploying `vortex-ts-registry` packages
- add option to force update dependecies to latest version for all/specific `vortex-ts-registry` dependencies
- ~~handle ctrl+c during node package install on docker. (currently it continues running in BG)~~
- ~~add new baseclass typescript package and do not include SOP, (do not normalize - to _) change `npm start` to `tsc` and test runs. Also generate .d.ts file in tsconfig.json~~
