# Contributing to Zstandard
We want to make contributing to this project as easy and transparent as
possible.

## Our Development Process
New versions are being developed in the "dev" branch,
or in their own feature branch.
When they are deemed ready for a release, they are merged into "release".

As a consequence, all contributions must stage first through "dev"
or their own feature branch.

## Pull Requests
We actively welcome your pull requests.

1. Fork the repo and create your branch from `dev`.
2. If you've added code that should be tested, add tests.
3. If you've changed APIs, update the documentation.
4. Ensure the test suite passes.
5. Make sure your code lints.
6. If you haven't already, complete the Contributor License Agreement ("CLA").

## Contributor License Agreement ("CLA")
In order to accept your pull request, we need you to submit a CLA. You only need
to do this once to work on any of Facebook's open source projects.

Complete your CLA here: <https://code.facebook.com/cla>

## Workflow
Zstd uses a branch-based workflow for making changes to the codebase. Typically, zstd
will use a new branch per sizable topic. For smaller changes, it is okay to lump multiple
related changes into a branch.

Our contribution process works in three main stages:
1. Local development
    * Update:
        * Checkout your fork of zstd if you have not already
        ```
        git checkout https://github.com/<username>/zstd
        cd zstd
        ```
        * Update your local dev branch
        ```
        git pull https://github.com/facebook/zstd dev
        git push origin dev
        ```
    * Topic and development:
        * Make a new branch on your fork about the topic you're developing for
        ```
        # branch names should be concise but sufficiently informative
        git checkout -b <branch-name>
        git push origin <branch-name>
        ```
        * Make commits and push
        ```
        # make some changes =
        git add -u && git commit -m <message>
        git push origin <branch-name>
        ```
        * Note: run local tests to ensure that your changes didn't break existing functionality
            * Quick check
            ```
            make check
            ```
            * Longer check
            ```
            make test
            ```
2. Code Review and CI tests
    * Ensure CI tests pass:
        * Before sharing anything to the community, create a pull request in your own fork against the dev branch
        and make sure that all GitHub Actions CI tests pass. See the Continuous Integration section below for more information.
        * Ensure that static analysis passes on your development machine. See the Static Analysis section
        below to see how to do this.
    * Create a pull request:
        * When you are ready to share you changes to the community, create a pull request from your branch
        to facebook:dev. You can do this very easily by clicking 'Create Pull Request' on your fork's home
        page.
        * From there, select the branch where you made changes as your source branch and facebook:dev
        as the destination.
        * Examine the diff presented between the two branches to make sure there is nothing unexpected.
    * Write a good pull request description:
        * While there is no strict template that our contributors follow, we would like them to
        sufficiently summarize and motivate the changes they are proposing. We recommend all pull requests,
        at least indirectly, address the following points.
            * Is this pull request important and why?
            * Is it addressing an issue? If so, what issue? (provide links for convenience please)
            * Is this a new feature? If so, why is it useful and/or necessary?
            * Are there background references and documents that reviewers should be aware of to properly assess this change?
        * Note: make sure to point out any design and architectural decisions that you made and the rationale behind them.
        * Note: if you have been working with a specific user and would like them to review your work, make sure you mention them using (@<username>)
    * Submit the pull request and iterate with feedback.
3. Merge and Release
    * Getting approval:
        * You will have to iterate on your changes with feedback from other collaborators to reach a point
        where your pull request can be safely merged.
        * To avoid too many comments on style and convention, make sure that you have a
        look at our style section below before creating a pull request.
        * Eventually, someone from the zstd team will approve your pull request and not long after merge it into
        the dev branch.
    * Housekeeping:
        * Most PRs are linked with one or more Github issues. If this is the case for your PR, make sure
        the corresponding issue is mentioned. If your change 'fixes' or completely addresses the
        issue at hand, then please indicate this by requesting that an issue be closed by commenting.
        * Just because your changes have been merged does not mean the topic or larger issue is complete. Remember
        that the change must make it to an official zstd release for it to be meaningful. We recommend
        that contributors track the activity on their pull request and corresponding issue(s) page(s) until
        their change makes it to the next release of zstd. Users will often discover bugs in your code or
        suggest ways to refine and improve your initial changes even after the pull request is merged.

## Static Analysis
Static analysis is a process for examining the correctness or validity of a program without actually
executing it. It usually helps us find many simple bugs. Zstd uses clang's `scan-build` tool for
static analysis. You can install it by following the instructions for your OS on https://clang-analyzer.llvm.org/scan-build.

Once installed, you can ensure that our static analysis tests pass on your local development machine
by running:
```
make staticAnalyze
```

In general, you can use `scan-build` to static analyze any build script. For example, to static analyze
just `contrib/largeNbDicts` and nothing else, you can run:

```
scan-build make -C contrib/largeNbDicts largeNbDicts
```

### Pitfalls of static analysis
`scan-build` is part of our regular CI suite. Other static analyzers are not.

It can be useful to look at additional static analyzers once in a while (and we do), but it's not a good idea to multiply the nb of analyzers run continuously at each commit and PR. The reasons are :

- Static analyzers are full of false positive. The signal to noise ratio is actually pretty low.
- A good CI policy is "zero-warning tolerance". That means that all issues must be solved, including false positives. This quickly becomes a tedious workload.
- Multiple static analyzers will feature multiple kind of false positives, sometimes applying to the same code but in different ways leading to :
   + tortuous code, trying to please multiple constraints, hurting readability and therefore maintenance. Sometimes, such complexity introduce other more subtle bugs, that are just out of scope of the analyzers.
   + sometimes, these constraints are mutually exclusive : if one try to solve one, the other static analyzer will complain, they can't be both happy at the same time.
- As if that was not enough, the list of false positives change with each version. It's hard enough to follow one static analyzer, but multiple ones with their own update agenda, this quickly becomes a massive velocity reducer.

This is different from running a static analyzer once in a while, looking at the output, and __cherry picking__ a few warnings that seem helpful, either because they detected a genuine risk of bug, or because it helps expressing the code in a way which is more readable or more difficult to misuse. These kinds of reports can be useful, and are accepted.

## Continuous Integration
CI tests run every time a pull request (PR) is created or updated. The exact tests
that get run will depend on the destination branch you specify. Some tests take
longer to run than others. Currently, our CI is set up to run a short
series of tests when creating a PR to the dev branch and a longer series of tests
when creating a PR to the release branch. You can look in the configuration files
of the respective CI platform for more information on what gets run when.

Most people will just want to create a PR with the destination set to their local dev
branch of zstd. You can then find the status of the tests on the PR's page. You can also
re-run tests and cancel running tests from the PR page or from the respective CI's dashboard.

Almost all of zstd's CI runs on GitHub Actions (configured at `.github/workflows`), which will automatically run on PRs to your
own fork. A small number of tests run on other services (e.g. Travis CI, Circle CI, Appveyor).
These require work to set up on your local fork, and (at least for Travis CI) cost money.
Therefore, if the PR on your local fork passes GitHub Actions, feel free to submit a PR
against the main repo.

### Third-party CI
A small number of tests cannot run on GitHub Actions, or have yet to be migrated.
For these, we use a variety of third-party services (listed below). It is not necessary to set
these up on your fork in order to contribute to zstd; however, we do link to instructions for those
who want earlier signal.

| Service   | Purpose                                                                                | Setup Links                                                                                | Config Path            |
|-----------|------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------|
| Travis CI | Used for testing on non-x86 architectures such as PowerPC                                                  | https://docs.travis-ci.com/user/tutorial/#to-get-started-with-travis-ci-using-github
 https://github.com/marketplace/travis-ci                     | `.travis.yml`          |
| AppVeyor  | Used for some Windows testing (e.g. cygwin, mingw)                                                         | https://www.appveyor.com/blog/2018/10/02/github-apps-integration/
 https://github.com/marketplace/appveyor                                         | `appveyor.yml`         |
| Cirrus CI | Used for testing on FreeBSD                                                                                | https://github.com/marketplace/cirrus-ci/                                                                                | `.cirrus.yml`          |
| Circle CI | Historically was used to provide faster signal,
 but we may be able to migrate these to Github Actions | https://circleci.com/docs/2.0/getting-started/#setting-up-circleci
 https://youtu.be/Js3hMUsSZ2c
 https://circleci.com/docs/2.0/enable-checks/ | `.circleci/config.yml` |

Note: the instructions linked above mostly cover how to set up a repository with CI from scratch.
The general idea should be the same for setting up CI on your fork of zstd, but you may have to
follow slightly different steps. In particular, please ignore any instructions related to setting up
config files (since zstd already has configs for each of these services).

## Performance
Performance is extremely important for zstd and we only merge pull requests whose performance
landscape and corresponding trade-offs have been adequately analyzed, reproduced, and presented.
This high bar for performance means that every PR which has the potential to
impact performance takes a very long time for us to properly review. That being said, we
always welcome contributions to improve performance (or worsen performance for the trade-off of
something else). Please keep the following in mind before submitting a performance related PR:

1. Zstd isn't as old as gzip but it has been around for time now and its evolution is
very well documented via past Github issues and pull requests. It may be the case that your
particular performance optimization has already been considered in the past. Please take some
time to search through old issues and pull requests using keywords specific to your
would-be PR. Of course, just because a topic has already been discussed (and perhaps rejected
on some grounds) in the past, doesn't mean it isn't worth bringing up again. But even in that case,
it will be helpful for you to have context from that topic's history before contributing.
2. The distinction between noise and actual performance gains can unfortunately be very subtle
especially when microbenchmarking extremely small wins or losses. The only remedy to getting
something subtle merged is extensive benchmarking. You will be doing us a great favor if you
take the time to run extensive, long-duration, and potentially cross-(os, platform, process, etc)
benchmarks on your end before submitting a PR. Of course, you will not be able to benchmark
your changes on every single processor and os out there (and neither will we) but do that best
you can:) We've added some things to think about when benchmarking below in the Benchmarking
Performance section which might be helpful for you.
3. Optimizing performance for a certain OS, processor vendor, compiler, or network system is a perfectly
legitimate thing to do as long as it does not harm the overall performance health of Zstd.
This is a hard balance to strike but please keep in mind other aspects of Zstd when
submitting changes that are clang-specific, windows-specific, etc.

## Benchmarking Performance
Performance microbenchmarking is a tricky subject but also essential for Zstd. We value empirical
testing over theoretical speculation. This guide it not perfect but for most scenarios, it
is a good place to start.

### Stability
Unfortunately, the most important aspect in being able to benchmark reliably is to have a stable
benchmarking machine. A virtual machine, a machine with shared resources, or your laptop
will typically not be stable enough to obtain reliable benchmark results. If you can get your
hands on a desktop, this is usually a better scenario.

Of course, benchmarking can be done on non-hyper-stable machines as well. You will just have to
do a little more work to ensure that you are in fact measuring the changes you've made and not
noise. Here are some things you can do to make your benchmarks more stable:

1. The most simple thing you can do to drastically improve the stability of your benchmark is
to run it multiple times and then aggregate the results of those runs. As a general rule of
thumb, the smaller the change you are trying to measure, the more samples of benchmark runs
you will have to aggregate over to get reliable results. Here are some additional things to keep in
mind when running multiple trials:
    * How you aggregate your samples are important. You might be tempted to use the mean of your
    results. While this is certainly going to be a more stable number than a raw single sample
    benchmark number, you might have more luck by taking the median. The mean is not robust to
    outliers whereas the median is. Better still, you could simply take the fastest speed your
    benchmark achieved on each run since that is likely the fastest your process will be
    capable of running your code. In our experience, this (aggregating by just taking the sample
    with the fastest running time) has been the most stable approach.
    * The more samples you have, the more stable your benchmarks should be. You can verify
    your improved stability by looking at the size of your confidence intervals as you
    increase your sample count. These should get smaller and smaller. Eventually hopefully
    smaller than the performance win you are expecting.
    * Most processors will take some time to get `hot` when running anything. The observations
    you collect during that time period will very different from the true performance number. Having
    a very large number of sample will help alleviate this problem slightly but you can also
    address is directly by simply not including the first `n` iterations of your benchmark in
    your aggregations. You can determine `n` by simply looking at the results from each iteration
    and then hand picking a good threshold after which the variance in results seems to stabilize.
2. You cannot really get reliable benchmarks if your host machine is simultaneously running
another cpu/memory-intensive application in the background. If you are running benchmarks on your
personal laptop for instance, you should close all applications (including your code editor and
browser) before running your benchmarks. You might also have invisible background applications
running. You can see what these are by looking at either Activity Monitor on Mac or Task Manager
on Windows. You will get more stable benchmark results of you end those processes as well.
    * If you have multiple cores, you can even run your benchmark on a reserved core to prevent
    pollution from other OS and user processes. There are a number of ways to do this depending
    on your OS:
        * On linux boxes, you have use https://github.com/lpechacek/cpuset.
        * On Windows, you can "Set Processor Affinity" using https://www.thewindowsclub.com/processor-affinity-windows
        * On Mac, you can try to use their dedicated affinity API https://developer.apple.com/library/archive/releasenotes/Performance/RN-AffinityAPI/#//apple_ref/doc/uid/TP40006635-CH1-DontLinkElementID_2
3. To benchmark, you will likely end up writing a separate c/c++ program that will link libzstd.
Dynamically linking your library will introduce some added variation (not a large amount but
definitely some). Statically linking libzstd will be more stable. Static libraries should
be enabled by default when building zstd.
4. Use a profiler with a good high resolution timer. See the section below on profiling for
details on this.
5. Disable frequency scaling, turbo boost and address space randomization (this will vary by OS)
6. Try to avoid storage. On some systems you can use tmpfs. Putting the program, inputs and outputs on
tmpfs avoids touching a real storage system, which can have a pretty big variability.

Also check our LLVM's guide on benchmarking here: https://llvm.org/docs/Benchmarking.html

### Zstd benchmark
The fastest signal you can get regarding your performance changes is via the in-build zstd cli
bench option. You can run Zstd as you typically would for your scenario using some set of options
and then additionally also specify the `-b#` option. Doing this will run our benchmarking pipeline
for that options you have just provided. If you want to look at the internals of how this
benchmarking script works, you can check out programs/benchzstd.c

For example: say you have made a change that you believe improves the speed of zstd level 1. The
very first thing you should use to assess whether you actually achieved any sort of improvement
is `zstd -b`. You might try to do something like this. Note: you can use the `-i` option to
specify a running time for your benchmark in seconds (default is 3 seconds).
Usually, the longer the running time, the more stable your results will be.

```
$ git checkout <commit-before-your-change>
$ make && cp zstd zstd-old
$ git checkout <commit-after-your-change>
$ make && cp zstd zstd-new
$ zstd-old -i5 -b1 <your-test-data>
 1<your-test-data>         :      8990 ->      3992 (2.252), 302.6 MB/s , 626.4 MB/s
$ zstd-new -i5 -b1 <your-test-data>
 1<your-test-data>         :      8990 ->      3992 (2.252), 302.8 MB/s , 628.4 MB/s
```

Unless your performance win is large enough to be visible despite the intrinsic noise
on your computer, benchzstd alone will likely not be enough to validate the impact of your
changes. For example, the results of the example above indicate that effectively nothing
changed but there could be a small <3% improvement that the noise on the host machine
obscured. So unless you see a large performance win (10-15% consistently) using just
this method of evaluation will not be sufficient.

### Profiling
There are a number of great profilers out there. We're going to briefly mention how you can
profile your code using `instruments` on mac, `perf` on linux and `visual studio profiler`
on Windows.

Say you have an idea for a change that you think will provide some good performance gains
for level 1 compression on Zstd. Typically this means, you have identified a section of
code that you think can be made to run faster.

The first thing you will want to do is make sure that the piece of code is actually taking up
a notable amount of time to run. It is usually not worth optimizing something which accounts for less than
0.0001% of the total running time. Luckily, there are tools to help with this.
Profilers will let you see how much time your code spends inside a particular function.
If your target code snippet is only part of a function, it might be worth trying to
isolate that snippet by moving it to its own function (this is usually not necessary but
might be).

Most profilers (including the profilers discussed below) will generate a call graph of
functions for you. Your goal will be to find your function of interest in this call graph
and then inspect the time spent inside of it. You might also want to look at the annotated
assembly which most profilers will provide you with.

#### Instruments
We will once again consider the scenario where you think you've identified a piece of code
whose performance can be improved upon. Follow these steps to profile your code using
Instruments.

1. Open Instruments
2. Select `Time Profiler` from the list of standard templates
3. Close all other applications except for your instruments window and your terminal
4. Run your benchmarking script from your terminal window
    * You will want a benchmark that runs for at least a few seconds (5 seconds will
    usually be long enough). This way the profiler will have something to work with
    and you will have ample time to attach your profiler to this process:)
    * I will just use benchzstd as my benchmarmking script for this example:
```
$ zstd -b1 -i5 <my-data> # this will run for 5 seconds
```
5. Once you run your benchmarking script, switch back over to instruments and attach your
process to the time profiler. You can do this by:
    * Clicking on the `All Processes` drop down in the top left of the toolbar.
    * Selecting your process from the dropdown. In my case, it is just going to be labeled
    `zstd`
    * Hitting the bright red record circle button on the top left of the toolbar
6. You profiler will now start collecting metrics from your benchmarking script. Once
you think you have collected enough samples (usually this is the case after 3 seconds of
recording), stop your profiler.
7. Make sure that in toolbar of the bottom window, `profile` is selected.
8. You should be able to see your call graph.
    * If you don't see the call graph or an incomplete call graph, make sure you have compiled
    zstd and your benchmarking script using debug flags. On mac and linux, this just means
    you will have to supply the `-g` flag alone with your build script. You might also
    have to provide the `-fno-omit-frame-pointer` flag
9. Dig down the graph to find your function call and then inspect it by double clicking
the list item. You will be able to see the annotated source code and the assembly side by
side.

#### Perf

This wiki has a pretty detailed tutorial on getting started working with perf so we'll
leave you to check that out of you're getting started:

https://perf.wiki.kernel.org/index.php/Tutorial

Some general notes on perf:
* Use `perf stat -r # <bench-program>` to quickly get some relevant timing and
counter statistics. Perf uses a high resolution timer and this is likely one
of the first things your team will run when assessing your PR.
* Perf has a long list of hardware counters that can be viewed with `perf --list`.
When measuring optimizations, something worth trying is to make sure the hardware
counters you expect to be impacted by your change are in fact being so. For example,
if you expect the L1 cache misses to decrease with your change, you can look at the
counter `L1-dcache-load-misses`
* Perf hardware counters will not work on a virtual machine.

#### Visual Studio

TODO

## Issues
We use GitHub issues to track public bugs. Please ensure your description is
clear and has sufficient instructions to be able to reproduce the issue.

Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
disclosure of security bugs. In those cases, please go through the process
outlined on that page and do not file a public issue.

## Coding Style
It's a pretty long topic, which is difficult to summarize in a single paragraph.
As a rule of thumbs, try to imitate the coding style of
similar lines of codes around your contribution.
The following is a non-exhaustive list of rules employed in zstd code base:

### C90
This code base is following strict C90 standard,
with 2 extensions : 64-bit `long long` types, and variadic macros.
This rule is applied strictly to code within `lib/` and `programs/`.
Sub-project in `contrib/` are allowed to use other conventions.

### C++ direct compatibility : symbol mangling
All public symbol declarations must be wrapped in `extern “C” { … }`,
so that this project can be compiled as C++98 code,
and linked into C++ applications.

### Minimal Frugal
This design requirement is fundamental to preserve the portability of the code base.
#### Dependencies
- Reduce dependencies to the minimum possible level.
  Any dependency should be considered “bad” by default,
  and only tolerated because it provides a service in a better way than can be achieved locally.
  The only external dependencies this repository tolerates are
  standard C libraries, and in rare cases, system level headers.
- Within `lib/`, this policy is even more drastic.
  The only external dependencies allowed are `<assert.h>`, `<stdlib.h>`, `<string.h>`,
  and even then, not directly.
  In particular, no function shall ever allocate on heap directly,
  and must use instead `ZSTD_malloc()` and equivalent.
  Other accepted non-symbol headers are `<stddef.h>` and `<limits.h>`.
- Within the project, there is a strict hierarchy of dependencies that must be respected.
  `programs/` is allowed to depend on `lib/`, but only its public API.
  Within `lib/`, `lib/common` doesn't depend on any other directory.
  `lib/compress` and `lib/decompress` shall not depend on each other.
  `lib/dictBuilder` can depend on `lib/common` and `lib/compress`, but not `lib/decompress`.
#### Resources
- Functions in `lib/` must use very little stack space,
  several dozens of bytes max.
  Everything larger must use the heap allocator,
  or require a scratch buffer to be emplaced manually.

### Naming
* All public symbols are prefixed with `ZSTD_`
  + private symbols, with a scope limited to their own unit, are free of this restriction.
    However, since `libzstd` source code can be amalgamated,
    each symbol name must attempt to be (and remain) unique.
    Avoid too generic names that could become ground for future collisions.
    This generally implies usage of some form of prefix.
* For symbols (functions and variables), naming convention is `PREFIX_camelCase`.
  + In some advanced cases, one can also find :
    - `PREFIX_prefix2_camelCase`
    - `PREFIX_camelCase_extendedQualifier`
* Multi-words names generally consist of an action followed by object:
  - for example : `ZSTD_createCCtx()`
* Prefer positive actions
  - `goBackward` rather than `notGoForward`
* Type names (`struct`, etc.) follow similar convention,
  except that they are allowed and even invited to start by an Uppercase letter.
  Example : `ZSTD_CCtx`, `ZSTD_CDict`
* Macro names are all Capital letters.
  The same composition rules (`PREFIX_NAME_QUALIFIER`) apply.
* File names are all lowercase letters.
  The convention is `snake_case`.
  File names **must** be unique across the entire code base,
  even when they stand in clearly separated directories.

### Qualifiers
* This code base is `const` friendly, if not `const` fanatical.
  Any variable that can be `const` (aka. read-only) **must** be `const`.
  Any pointer which content will not be modified must be `const`.
  This property is then controlled at compiler level.
  `const` variables are an important signal to readers that this variable isn't modified.
  Conversely, non-const variables are a signal to readers to watch out for modifications later on in the function.
* If a function must be inlined, mention it explicitly,
  using project's own portable macros, such as `FORCE_INLINE_ATTR`,
  defined in `lib/common/compiler.h`.

### Debugging
* **Assertions** are welcome, and should be used very liberally,
  to control any condition the code expects for its correct execution.
  These assertion checks will be run in debug builds, and disabled in production.
* For traces, this project provides its own debug macros,
  in particular `DEBUGLOG(level, ...)`, defined in `lib/common/debug.h`.

### Code documentation
* Avoid code documentation that merely repeats what the code is already stating.
  Whenever applicable, prefer employing the code as the primary way to convey explanations.
  Example 1 : `int nbTokens = n;` instead of `int i = n; /* i is a nb of tokens *./`.
  Example 2 : `assert(size > 0);` instead of `/* here, size should be positive */`.
* At declaration level, the documentation explains how to use the function or variable
  and when applicable why it's needed, of the scenarios where it can be useful.
* At implementation level, the documentation explains the general outline of the algorithm employed,
  and when applicable why this specific choice was preferred.

### General layout
* 4 spaces for indentation rather than tabs
* Code documentation shall directly precede function declaration or implementation
* Function implementations and its code documentation should be preceded and followed by an empty line

## License
By contributing to Zstandard, you agree that your contributions will be licensed
under both the [LICENSE](LICENSE) file and the [COPYING](COPYING) file in the root directory of this source tree.


__Zstandard__, or `zstd` as short version, is a fast lossless compression algorithm,
targeting real-time compression scenarios at zlib-level and better compression ratios.
It's backed by a very fast entropy stage, provided by [Huff0 and FSE library](https://github.com/Cyan4973/FiniteStateEntropy).

Zstandard's format is stable and documented in [RFC8878](https://datatracker.ietf.org/doc/html/rfc8878). Multiple independent implementations are already available.
This repository represents the reference implementation, provided as an open-source dual [BSD](LICENSE) OR [GPLv2](COPYING) licensed **C** library,
and a command line utility producing and decoding `.zst`, `.gz`, `.xz` and `.lz4` files.
Should your project require another programming language,
a list of known ports and bindings is provided on [Zstandard homepage](https://facebook.github.io/zstd/#other-languages).

**Development branch status:**

[![Build Status][travisDevBadge]][travisLink]
[![Build status][CircleDevBadge]][CircleLink]
[![Build status][CirrusDevBadge]][CirrusLink]
[![Fuzzing Status][OSSFuzzBadge]][OSSFuzzLink]

[travisDevBadge]: https://api.travis-ci.com/facebook/zstd.svg?branch=dev "Continuous Integration test suite"
[travisLink]: https://travis-ci.com/facebook/zstd
[CircleDevBadge]: https://circleci.com/gh/facebook/zstd/tree/dev.svg?style=shield "Short test suite"
[CircleLink]: https://circleci.com/gh/facebook/zstd
[CirrusDevBadge]: https://api.cirrus-ci.com/github/facebook/zstd.svg?branch=dev
[CirrusLink]: https://cirrus-ci.com/github/facebook/zstd
[OSSFuzzBadge]: https://oss-fuzz-build-logs.storage.googleapis.com/badges/zstd.svg
[OSSFuzzLink]: https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:zstd

## Benchmarks

For reference, several fast compression algorithms were tested and compared
on a desktop featuring a Core i7-9700K CPU @ 4.9GHz
and running Ubuntu 20.04 (`Linux ubu20 5.15.0-101-generic`),
using [lzbench], an open-source in-memory benchmark by @inikep
compiled with [gcc] 9.4.0,
on the [Silesia compression corpus].

[lzbench]: https://github.com/inikep/lzbench
[Silesia compression corpus]: https://sun.aei.polsl.pl//~sdeor/index.php?page=silesia
[gcc]: https://gcc.gnu.org/

| Compressor name         | Ratio | Compression| Decompress.|
| ---------------         | ------| -----------| ---------- |
| **zstd 1.5.6 -1**       | 2.887 |   510 MB/s |  1580 MB/s |
| [zlib] 1.2.11 -1        | 2.743 |    95 MB/s |   400 MB/s |
| brotli 1.0.9 -0         | 2.702 |   395 MB/s |   430 MB/s |
| **zstd 1.5.6 --fast=1** | 2.437 |   545 MB/s |  1890 MB/s |
| **zstd 1.5.6 --fast=3** | 2.239 |   650 MB/s |  2000 MB/s |
| quicklz 1.5.0 -1        | 2.238 |   525 MB/s |   750 MB/s |
| lzo1x 2.10 -1           | 2.106 |   650 MB/s |   825 MB/s |
| [lz4] 1.9.4             | 2.101 |   700 MB/s |  4000 MB/s |
| lzf 3.6 -1              | 2.077 |   420 MB/s |   830 MB/s |
| snappy 1.1.9            | 2.073 |   530 MB/s |  1660 MB/s |

[zlib]: https://www.zlib.net/
[lz4]: https://lz4.github.io/lz4/

The negative compression levels, specified with `--fast=#`,
offer faster compression and decompression speed
at the cost of compression ratio.

Zstd can also offer stronger compression ratios at the cost of compression speed.
Speed vs Compression trade-off is configurable by small increments.
Decompression speed is preserved and remains roughly the same at all settings,
a property shared by most LZ compression algorithms, such as [zlib] or lzma.

The following tests were run
on a server running Linux Debian (`Linux version 4.14.0-3-amd64`)
with a Core i7-6700K CPU @ 4.0GHz,
using [lzbench], an open-source in-memory benchmark by @inikep
compiled with [gcc] 7.3.0,
on the [Silesia compression corpus].

Compression Speed vs Ratio | Decompression Speed
---------------------------|--------------------
![Compression Speed vs Ratio](doc/images/CSpeed2.png "Compression Speed vs Ratio") | ![Decompression Speed](doc/images/DSpeed3.png "Decompression Speed")

A few other algorithms can produce higher compression ratios at slower speeds, falling outside of the graph.
For a larger picture including slow modes, [click on this link](doc/images/DCspeed5.png).

## The case for Small Data compression

Previous charts provide results applicable to typical file and stream scenarios (several MB). Small data comes with different perspectives.

The smaller the amount of data to compress, the more difficult it is to compress. This problem is common to all compression algorithms, and reason is, compression algorithms learn from past data how to compress future data. But at the beginning of a new data set, there is no "past" to build upon.

To solve this situation, Zstd offers a __training mode__, which can be used to tune the algorithm for a selected type of data.
Training Zstandard is achieved by providing it with a few samples (one file per sample). The result of this training is stored in a file called "dictionary", which must be loaded before compression and decompression.
Using this dictionary, the compression ratio achievable on small data improves dramatically.

The following example uses the `github-users` [sample set](https://github.com/facebook/zstd/releases/tag/v1.1.3), created from [github public API](https://developer.github.com/v3/users/#get-all-users).
It consists of roughly 10K records weighing about 1KB each.

Compression Ratio | Compression Speed | Decompression Speed
------------------|-------------------|--------------------
![Compression Ratio](doc/images/dict-cr.png "Compression Ratio") | ![Compression Speed](doc/images/dict-cs.png "Compression Speed") | ![Decompression Speed](doc/images/dict-ds.png "Decompression Speed")

These compression gains are achieved while simultaneously providing _faster_ compression and decompression speeds.

Training works if there is some correlation in a family of small data samples. The more data-specific a dictionary is, the more efficient it is (there is no _universal dictionary_).
Hence, deploying one dictionary per type of data will provide the greatest benefits.
Dictionary gains are mostly effective in the first few KB. Then, the compression algorithm will gradually use previously decoded content to better compress the rest of the file.

### Dictionary compression How To:

1. Create the dictionary

   `zstd --train FullPathToTrainingSet/* -o dictionaryName`

2. Compress with dictionary

   `zstd -D dictionaryName FILE`

3. Decompress with dictionary

   `zstd -D dictionaryName --decompress FILE.zst`

## Build instructions

`make` is the officially maintained build system of this project.
All other build systems are "compatible" and 3rd-party maintained,
they may feature small differences in advanced options.
When your system allows it, prefer using `make` to build `zstd` and `libzstd`.

### Makefile

If your system is compatible with standard `make` (or `gmake`),
invoking `make` in root directory will generate `zstd` cli in root directory.
It will also create `libzstd` into `lib/`.

Other available options include:
- `make install` : create and install zstd cli, library and man pages
- `make check` : create and run `zstd`, test its behavior on local platform

The `Makefile` follows the [GNU Standard Makefile conventions](https://www.gnu.org/prep/standards/html_node/Makefile-Conventions.html),
allowing staged install, standard flags, directory variables and command variables.

For advanced use cases, specialized compilation flags which control binary generation
are documented in [`lib/README.md`](lib/README.md#modular-build) for the `libzstd` library
and in [`programs/README.md`](programs/README.md#compilation-variables) for the `zstd` CLI.

### cmake

A `cmake` project generator is provided within `build/cmake`.
It can generate Makefiles or other build scripts
to create `zstd` binary, and `libzstd` dynamic and static libraries.

By default, `CMAKE_BUILD_TYPE` is set to `Release`.

#### Support for Fat (Universal2) Output

`zstd` can be built and installed with support for both Apple Silicon (M1/M2) as well as Intel by using CMake's Universal2 support.
To perform a Fat/Universal2 build and install use the following commands:

```bash
cmake -B build-cmake-debug -S build/cmake -G Ninja -DCMAKE_OSX_ARCHITECTURES="x86_64;x86_64h;arm64"
cd build-cmake-debug
ninja
sudo ninja install
```

### Meson

A Meson project is provided within [`build/meson`](build/meson). Follow
build instructions in that directory.

You can also take a look at [`.travis.yml`](.travis.yml) file for an
example about how Meson is used to build this project.

Note that default build type is **release**.

### VCPKG
You can build and install zstd [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager:

    git clone https://github.com/Microsoft/vcpkg.git
    cd vcpkg
    ./bootstrap-vcpkg.sh
    ./vcpkg integrate install
    ./vcpkg install zstd

The zstd port in vcpkg is kept up to date by Microsoft team members and community contributors.
If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository.

### Conan

You can install pre-built binaries for zstd or build it from source using [Conan](https://conan.io/). Use the following command:

```bash
conan install --requires="zstd/[*]" --build=missing
```

The zstd Conan recipe is kept up to date by Conan maintainers and community contributors.
If the version is out of date, please [create an issue or pull request](https://github.com/conan-io/conan-center-index) on the ConanCenterIndex repository.

### Visual Studio (Windows)

Going into `build` directory, you will find additional possibilities:
- Projects for Visual Studio 2005, 2008 and 2010.
  + VS2010 project is compatible with VS2012, VS2013, VS2015 and VS2017.
- Automated build scripts for Visual compiler by [@KrzysFR](https://github.com/KrzysFR), in `build/VS_scripts`,
  which will build `zstd` cli and `libzstd` library without any need to open Visual Studio solution.

### Buck

You can build the zstd binary via buck by executing: `buck build programs:zstd` from the root of the repo.
The output binary will be in `buck-out/gen/programs/`.

### Bazel

You easily can integrate zstd into your Bazel project by using the module hosted on the [Bazel Central Repository](https://registry.bazel.build/modules/zstd).

## Testing

You can run quick local smoke tests by running `make check`.
If you can't use `make`, execute the `playTest.sh` script from the `src/tests` directory.
Two env variables `$ZSTD_BIN` and `$DATAGEN_BIN` are needed for the test script to locate the `zstd` and `datagen` binary.
For information on CI testing, please refer to `TESTING.md`.

## Status

Zstandard is currently deployed within Facebook and many other large cloud infrastructures.
It is run continuously to compress large amounts of data in multiple formats and use cases.
Zstandard is considered safe for production environments.

## License

Zstandard is dual-licensed under [BSD](LICENSE) OR [GPLv2](COPYING).

## Contributing

The `dev` branch is the one where all contributions are merged before reaching `release`.
If you plan to propose a patch, please commit into the `dev` branch, or its own feature branch.
Direct commit to `release` are not permitted.
For more information, please read [CONTRIBUTING](CONTRIBUTING.md).

Perforator is a cluster-wide continuous profiling tool designed for large data centers


# Reporting and Fixing Security Issues

Please do not open GitHub issues or pull requests - this makes the problem immediately visible to everyone, including malicious actors. Security issues in this open source project can be safely reported via the Meta Bug Bounty program:

https://www.facebook.com/whitehat

Meta's security team will triage your report and determine whether or not is it eligible for a bounty under our program.

# Receiving Vulnerability Notifications

In the case that a significant security vulnerability is reported to us or discovered by us---without being publicly known---we will, at our discretion, notify high-profile, high-exposure users of Zstandard ahead of our public disclosure of the issue and associated fix.

If you believe your project would benefit from inclusion in this list, please reach out to one of the maintainers.

<!-- Note to maintainers: this list is kept [here](https://fburl.com/wiki/cgc1l62x). -->


Testing
=======

Zstandard CI testing is split up into three sections:
short, medium, and long tests.

Short Tests
-----------
Short tests run on CircleCI for new commits on every branch and pull request.
They consist of the following tests:
- Compilation on all supported targets (x86, x86_64, ARM, AArch64, PowerPC, and PowerPC64)
- Compilation on various versions of gcc, clang, and g++
- `tests/playTests.sh` on x86_64, without the tests on long data (CLI tests)
- Small tests (`tests/legacy.c`, `tests/longmatch.c`) on x64_64

Medium Tests
------------
Medium tests run on every commit and pull request to `dev` branch, on TravisCI.
They consist of the following tests:
- The following tests run with UBsan and Asan on x86_64 and x86, as well as with
  Msan on x86_64
  - `tests/playTests.sh --test-large-data`
  - Fuzzer tests: `tests/fuzzer.c`, `tests/zstreamtest.c`, and `tests/decodecorpus.c`
- `tests/zstreamtest.c` under Tsan (streaming mode, including multithreaded mode)
- Valgrind Test (`make -C tests test-valgrind`) (testing CLI and fuzzer under `valgrind`)
- Fuzzer tests (see above) on ARM, AArch64, PowerPC, and PowerPC64

Long Tests
----------
Long tests run on all commits to `release` branch,
and once a day on the current version of `dev` branch,
on TravisCI.
They consist of the following tests:
- Entire test suite (including fuzzers and some other specialized tests) on:
  - x86_64 and x86 with UBsan and Asan
  - x86_64 with Msan
  - ARM, AArch64, PowerPC, and PowerPC64
- Streaming mode fuzzer with Tsan (for the `zstdmt` testing)
- ZlibWrapper tests, including under valgrind
- Versions test (ensuring `zstd` can decode files from all previous versions)
- `pzstd` with asan and tsan, as well as in 32-bits mode
- Testing `zstd` with legacy mode off
- Entire test suite and make install on macOS


ASTTokens
=========

.. image:: https://img.shields.io/pypi/v/asttokens.svg
    :target: https://pypi.python.org/pypi/asttokens/
.. image:: https://img.shields.io/pypi/pyversions/asttokens.svg
    :target: https://pypi.python.org/pypi/asttokens/
.. image:: https://github.com/gristlabs/asttokens/actions/workflows/build-and-test.yml/badge.svg
    :target: https://github.com/gristlabs/asttokens/actions/workflows/build-and-test.yml
.. image:: https://readthedocs.org/projects/asttokens/badge/?version=latest
    :target: http://asttokens.readthedocs.io/en/latest/index.html
.. image:: https://coveralls.io/repos/github/gristlabs/asttokens/badge.svg
    :target: https://coveralls.io/github/gristlabs/asttokens

.. Start of user-guide

The ``asttokens`` module annotates Python abstract syntax trees (ASTs) with the positions of tokens
and text in the source code that generated them.

It makes it possible for tools that work with logical AST nodes to find the particular text that
resulted in those nodes, for example for automated refactoring or highlighting.

Installation
------------
asttokens is available on PyPI: https://pypi.python.org/pypi/asttokens/::

    pip install asttokens

The code is on GitHub: https://github.com/gristlabs/asttokens.

The API Reference is here: http://asttokens.readthedocs.io/en/latest/api-index.html.

Usage
-----

ASTTokens can annotate both trees built by `ast <https://docs.python.org/2/library/ast.html>`_,
AND those built by `astroid <https://github.com/PyCQA/astroid>`_.

Here's an example:

.. code-block:: python

    import asttokens, ast
    source = "Robot('blue').walk(steps=10*n)"
    atok = asttokens.ASTTokens(source, parse=True)

Once the tree has been marked, nodes get ``.first_token``, ``.last_token`` attributes, and
the ``ASTTokens`` object offers helpful methods:

.. code-block:: python

    attr_node = next(n for n in ast.walk(atok.tree) if isinstance(n, ast.Attribute))
    print(atok.get_text(attr_node))
    start, end = attr_node.last_token.startpos, attr_node.last_token.endpos
    print(atok.text[:start] + 'RUN' + atok.text[end:])

Which produces this output:

.. code-block:: text

    Robot('blue').walk
    Robot('blue').RUN(steps=10*n)

The ``ASTTokens`` object also offers methods to walk and search the list of tokens that make up
the code (or a particular AST node), which is more useful and powerful than dealing with the text
directly.

Contribute
----------

To contribute:

1. Fork this repository, and clone your fork.
2. Install the package with test dependencies (ideally in a virtualenv) with::

    pip install -e '.[test]'

3. Run tests in your current interpreter with the command ``pytest`` or ``python -m pytest``.
4. Run tests across all supported interpreters with the ``tox`` command. You will need to have the interpreters installed separately. We recommend ``pyenv`` for that. Use ``tox -p auto`` to run the tests in parallel.
5. By default certain tests which take a very long time to run are skipped, but they are run in CI.
   These are marked using the ``pytest`` marker ``slow`` and can be run on their own with ``pytest -m slow`` or as part of the full suite with ``pytest -m ''``.


# executing

[![Build Status](https://github.com/alexmojaki/executing/workflows/Tests/badge.svg?branch=master)](https://github.com/alexmojaki/executing/actions) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/executing/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/executing?branch=master) [![Supports Python versions 3.5+, including PyPy](https://img.shields.io/pypi/pyversions/executing.svg)](https://pypi.python.org/pypi/executing)

This mini-package lets you get information about what a frame is currently doing, particularly the AST node being executed.

* [Usage](#usage)
    * [Getting the AST node](#getting-the-ast-node)
    * [Getting the source code of the node](#getting-the-source-code-of-the-node)
    * [Getting the `__qualname__` of the current function](#getting-the-__qualname__-of-the-current-function)
    * [The Source class](#the-source-class)
* [Installation](#installation)
* [How does it work?](#how-does-it-work)
* [Is it reliable?](#is-it-reliable)
* [Which nodes can it identify?](#which-nodes-can-it-identify)
* [Projects that use this](#projects-that-use-this)

## Usage

### Getting the AST node

```python
import executing

node = executing.Source.executing(frame).node
```

Then `node` will be an AST node (from the `ast` standard library module) or None if the node couldn't be identified (which may happen often and should always be checked).

`node` will always be the same instance for multiple calls with frames at the same point of execution.

If you have a traceback object, pass it directly to `Source.executing()` rather than the `tb_frame` attribute to get the correct node.

### Getting the source code of the node

For this you will need to separately install the [`asttokens`](https://github.com/gristlabs/asttokens) library, then obtain an `ASTTokens` object:

```python
executing.Source.executing(frame).source.asttokens()
```

or:

```python
executing.Source.for_frame(frame).asttokens()
```

or use one of the convenience methods:

```python
executing.Source.executing(frame).text()
executing.Source.executing(frame).text_range()
```

### Getting the `__qualname__` of the current function

```python
executing.Source.executing(frame).code_qualname()
```

or:

```python
executing.Source.for_frame(frame).code_qualname(frame.f_code)
```

### The `Source` class

Everything goes through the `Source` class. Only one instance of the class is created for each filename. Subclassing it to add more attributes on creation or methods is recommended. The classmethods such as `executing` will respect this. See the source code and docstrings for more detail.

## Installation

    pip install executing

If you don't like that you can just copy the file `executing.py`, there are no dependencies (but of course you won't get updates).

## How does it work?

Suppose the frame is executing this line:

```python
self.foo(bar.x)
```

and in particular it's currently obtaining the attribute `self.foo`. Looking at the bytecode, specifically `frame.f_code.co_code[frame.f_lasti]`, we can tell that it's loading an attribute, but it's not obvious which one. We can narrow down the statement being executed using `frame.f_lineno` and find the two `ast.Attribute` nodes representing `self.foo` and `bar.x`. How do we find out which one it is, without recreating the entire compiler in Python?

The trick is to modify the AST slightly for each candidate expression and observe the changes in the bytecode instructions. We change the AST to this:

```python
(self.foo ** 'longuniqueconstant')(bar.x)
```

and compile it, and the bytecode will be almost the same but there will be two new instructions:

    LOAD_CONST 'longuniqueconstant'
    BINARY_POWER

and just before that will be a `LOAD_ATTR` instruction corresponding to `self.foo`. Seeing that it's in the same position as the original instruction lets us know we've found our match.

## Is it reliable?

Yes - if it identifies a node, you can trust that it's identified the correct one. The tests are very thorough - in addition to unit tests which check various situations directly, there are property tests against a large number of files (see the filenames printed in [this build](https://travis-ci.org/alexmojaki/executing/jobs/557970457)) with real code. Specifically, for each file, the tests:

 1. Identify as many nodes as possible from all the bytecode instructions in the file, and assert that they are all distinct
 2. Find all the nodes that should be identifiable, and assert that they were indeed identified somewhere

In other words, it shows that there is a one-to-one mapping between the nodes and the instructions that can be handled. This leaves very little room for a bug to creep in.

Furthermore, `executing` checks that the instructions compiled from the modified AST exactly match the original code save for a few small known exceptions. This accounts for all the quirks and optimisations in the interpreter.

## Which nodes can it identify?

Currently it works in almost all cases for the following `ast` nodes:

 - `Call`, e.g. `self.foo(bar)`
 - `Attribute`, e.g. `point.x`
 - `Subscript`, e.g. `lst[1]`
 - `BinOp`, e.g. `x + y` (doesn't include `and` and `or`)
 - `UnaryOp`, e.g. `-n` (includes `not` but only works sometimes)
 - `Compare` e.g. `a < b` (not for chains such as `0 < p < 1`)

The plan is to extend to more operations in the future.

## Projects that use this

### My Projects

- **[`stack_data`](https://github.com/alexmojaki/stack_data)**: Extracts data from stack frames and tracebacks, particularly to display more useful tracebacks than the default. Also uses another related library of mine: **[`pure_eval`](https://github.com/alexmojaki/pure_eval)**.
- **[`futurecoder`](https://futurecoder.io/)**: Highlights the executing node in tracebacks using `executing` via `stack_data`, and provides debugging with `snoop`.
- **[`snoop`](https://github.com/alexmojaki/snoop)**: A feature-rich and convenient debugging library. Uses `executing` to show the operation which caused an exception and to allow the `pp` function to display the source of its arguments.
- **[`heartrate`](https://github.com/alexmojaki/heartrate)**: A simple real time visualisation of the execution of a Python program. Uses `executing` to highlight currently executing operations, particularly in each frame of the stack trace.
- **[`sorcery`](https://github.com/alexmojaki/sorcery)**: Dark magic delights in Python. Uses `executing` to let special callables called spells know where they're being called from.

### Projects I've contributed to

- **[`IPython`](https://github.com/ipython/ipython/pull/12150)**: Highlights the executing node in tracebacks using `executing` via [`stack_data`](https://github.com/alexmojaki/stack_data).
- **[`icecream`](https://github.com/gruns/icecream)**: 🍦 Sweet and creamy print debugging. Uses `executing` to identify where `ic` is called and print its arguments.
- **[`friendly_traceback`](https://github.com/friendly-traceback/friendly-traceback)**: Uses `stack_data` and `executing` to pinpoint the cause of errors and provide helpful explanations.
- **[`python-devtools`](https://github.com/samuelcolvin/python-devtools)**: Uses `executing` for print debugging similar to `icecream`.
- **[`sentry_sdk`](https://github.com/getsentry/sentry-python)**: Add the integration `sentry_sdk.integrations.executingExecutingIntegration()` to show the function `__qualname__` in each frame in sentry events.
- **[`varname`](https://github.com/pwwang/python-varname)**: Dark magics about variable names in python. Uses `executing` to find where its various magical functions like `varname` and `nameof` are called from.


iniconfig: brain-dead simple parsing of ini files
=======================================================

iniconfig is a small and simple INI-file parser module
having a unique set of features:

* maintains order of sections and entries
* supports multi-line values with or without line-continuations
* supports "#" comments everywhere
* raises errors with proper line-numbers
* no bells and whistles like automatic substitutions
* iniconfig raises an Error if two sections have the same name.

If you encounter issues or have feature wishes please report them to:

    https://github.com/RonnyPfannschmidt/iniconfig/issues

Basic Example
===================================

If you have an ini file like this:

.. code-block:: ini

    # content of example.ini
    [section1] # comment
    name1=value1  # comment
    name1b=value1,value2  # comment

    [section2]
    name2=
        line1
        line2

then you can do:

.. code-block:: pycon

    >>> import iniconfig
    >>> ini = iniconfig.IniConfig("example.ini")
    >>> ini['section1']['name1'] # raises KeyError if not exists
    'value1'
    >>> ini.get('section1', 'name1b', [], lambda x: x.split(","))
    ['value1', 'value2']
    >>> ini.get('section1', 'notexist', [], lambda x: x.split(","))
    []
    >>> [x.name for x in list(ini)]
    ['section1', 'section2']
    >>> list(list(ini)[0].items())
    [('name1', 'value1'), ('name1b', 'value1,value2')]
    >>> 'section1' in ini
    True
    >>> 'inexistendsection' in ini
    False


.. image:: https://img.shields.io/pypi/v/jaraco.collections.svg
   :target: https://pypi.org/project/jaraco.collections

.. image:: https://img.shields.io/pypi/pyversions/jaraco.collections.svg

.. image:: https://github.com/jaraco/jaraco.collections/actions/workflows/main.yml/badge.svg
   :target: https://github.com/jaraco/jaraco.collections/actions?query=workflow%3A%22tests%22
   :alt: tests

.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
    :target: https://github.com/astral-sh/ruff
    :alt: Ruff

.. image:: https://readthedocs.org/projects/jaracocollections/badge/?version=latest
   :target: https://jaracocollections.readthedocs.io/en/latest/?badge=latest

.. image:: https://img.shields.io/badge/skeleton-2024-informational
   :target: https://blog.jaraco.com/skeleton

.. image:: https://tidelift.com/badges/package/pypi/jaraco.collections
   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.collections?utm_source=pypi-jaraco.collections&utm_medium=readme

Models and classes to supplement the stdlib 'collections' module.

See the docs, linked above, for descriptions and usage examples.

Highlights include:

- RangeMap: A mapping that accepts a range of values for keys.
- Projection: A subset over an existing mapping.
- KeyTransformingDict: Generalized mapping with keys transformed by a function.
- FoldedCaseKeyedDict: A dict whose string keys are case-insensitive.
- BijectiveMap: A map where keys map to values and values back to their keys.
- ItemsAsAttributes: A mapping mix-in exposing items as attributes.
- IdentityOverrideMap: A map whose keys map by default to themselves unless overridden.
- FrozenDict: A hashable, immutable map.
- Enumeration: An object whose keys are enumerated.
- Everything: A container that contains all things.
- Least, Greatest: Objects that are always less than or greater than any other.
- pop_all: Return all items from the mutable sequence and remove them from that sequence.
- DictStack: A stack of dicts, great for sharing scopes.
- WeightedLookup: A specialized RangeMap for selecting an item by weights.

For Enterprise
==============

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

`Learn more <https://tidelift.com/subscription/pkg/pypi-jaraco.collections?utm_source=pypi-jaraco.collections&utm_medium=referral&utm_campaign=github>`_.


.. image:: https://img.shields.io/pypi/v/jaraco.context.svg
   :target: https://pypi.org/project/jaraco.context

.. image:: https://img.shields.io/pypi/pyversions/jaraco.context.svg

.. image:: https://github.com/jaraco/jaraco.context/actions/workflows/main.yml/badge.svg
   :target: https://github.com/jaraco/jaraco.context/actions?query=workflow%3A%22tests%22
   :alt: tests

.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
    :target: https://github.com/astral-sh/ruff
    :alt: Ruff

.. image:: https://readthedocs.org/projects/jaracocontext/badge/?version=latest
   :target: https://jaracocontext.readthedocs.io/en/latest/?badge=latest

.. image:: https://img.shields.io/badge/skeleton-2024-informational
   :target: https://blog.jaraco.com/skeleton

.. image:: https://tidelift.com/badges/package/pypi/jaraco.context
   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=readme

Highlights
==========

See the docs linked from the badge above for the full details, but here are some features that may be of interest.

- ``ExceptionTrap`` provides a general-purpose wrapper for trapping exceptions and then acting on the outcome. Includes ``passes`` and ``raises`` decorators to replace the result of a wrapped function by a boolean indicating the outcome of the exception trap. See `this keyring commit <https://github.com/jaraco/keyring/commit/a85a7cbc6c909f8121660ed1f7b487f99a1c2bf7>`_ for an example of it in production.
- ``suppress`` simply enables ``contextlib.suppress`` as a decorator.
- ``on_interrupt`` is a decorator used by CLI entry points to affect the handling of a ``KeyboardInterrupt``. Inspired by `Lucretiel/autocommand#18 <https://github.com/Lucretiel/autocommand/issues/18>`_.
- ``pushd`` is similar to pytest's ``monkeypatch.chdir`` or path's `default context <https://path.readthedocs.io/en/latest/api.html>`_, changes the current working directory for the duration of the context.
- ``tarball`` will download a tarball, extract it, change directory, yield, then clean up after. Convenient when working with web assets.
- ``null`` is there for those times when one code branch needs a context and the other doesn't; this null context provides symmetry across those branches.

For Enterprise
==============

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

`Learn more <https://tidelift.com/subscription/pkg/pypi-jaraco.context?utm_source=pypi-jaraco.context&utm_medium=referral&utm_campaign=github>`_.


.. image:: https://img.shields.io/pypi/v/jaraco.text.svg
   :target: https://pypi.org/project/jaraco.text

.. image:: https://img.shields.io/pypi/pyversions/jaraco.text.svg

.. image:: https://github.com/jaraco/jaraco.text/actions/workflows/main.yml/badge.svg
   :target: https://github.com/jaraco/jaraco.text/actions?query=workflow%3A%22tests%22
   :alt: tests

.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json
    :target: https://github.com/astral-sh/ruff
    :alt: Ruff

.. image:: https://readthedocs.org/projects/jaracotext/badge/?version=latest
   :target: https://jaracotext.readthedocs.io/en/latest/?badge=latest

.. image:: https://img.shields.io/badge/skeleton-2024-informational
   :target: https://blog.jaraco.com/skeleton

.. image:: https://tidelift.com/badges/package/pypi/jaraco.text
   :target: https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=readme

This package provides handy routines for dealing with text, such as
wrapping, substitution, trimming, stripping, prefix and suffix removal,
line continuation, indentation, comment processing, identifier processing,
values parsing, case insensitive comparison, and more. See the docs
(linked in the badge above) for the detailed documentation and examples.

Layouts
=======

One of the features of this package is the layouts module, which
provides a simple example of translating keystrokes from one keyboard
layout to another::

    echo qwerty | python -m jaraco.text.to-dvorak
    ',.pyf
    echo  "',.pyf" | python -m jaraco.text.to-qwerty
    qwerty

Newline Reporting
=================

Need to know what newlines appear in a file?

::

    $ python -m jaraco.text.show-newlines README.rst
    newline is '\n'

For Enterprise
==============

Available as part of the Tidelift Subscription.

This project and the maintainers of thousands of other packages are working with Tidelift to deliver one enterprise subscription that covers all of the open source you use.

`Learn more <https://tidelift.com/subscription/pkg/pypi-jaraco.text?utm_source=pypi-jaraco.text&utm_medium=referral&utm_campaign=github>`_.


# Matplotlib Inline Back-end for IPython and Jupyter

This package provides support for matplotlib to display figures directly inline in the Jupyter notebook and related clients, as shown below.

## Installation

With conda:

```bash
conda install -c conda-forge matplotlib-inline
```

With pip:

```bash
pip install matplotlib-inline
```

## Usage

Note that in current versions of JupyterLab and Jupyter Notebook, the explicit use of the `%matplotlib inline` directive is not needed anymore, though other third-party clients may still require it.

This will produce a figure immediately below:

```python
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 3*np.pi, 500)
plt.plot(x, np.sin(x**2))
plt.title('A simple chirp');
```

## License

Licensed under the terms of the BSD 3-Clause License, by the IPython Development Team (see `LICENSE` file).


mypy-protobuf: Generate mypy stub files from protobuf specs

[![CI](https://github.com/nipunn1313/mypy-protobuf/workflows/CI/badge.svg)](https://github.com/nipunn1313/mypy-protobuf/actions?query=branch%3Amain)
[![pypi](https://img.shields.io/pypi/v/mypy-protobuf?logo=Pypi)](https://pypi.org/project/mypy-protobuf/)
[![license](https://img.shields.io/github/license/nipunn1313/mypy-protobuf)](https://github.com/nipunn1313/mypy-protobuf/blob/main/LICENSE)
===========================================================

2.10 is the last version of mypy-protobuf which supports targeting python 2.7.

Built originally with love at [Dropbox](https://github.com/dropbox)

See [Changelog](CHANGELOG.md) for recent changes.

## Requirements to run mypy-protobuf

Earlier releases might work, but aren't tested

- [protoc >= 23.4](https://github.com/protocolbuffers/protobuf/releases)
- [python-protobuf >= 4.25.3](https://pypi.org/project/protobuf/) - matching protoc release
- [python >= 3.8](https://www.python.org/downloads/source/) - for running mypy-protobuf plugin.

## Requirements to run typecheckers on stubs generated by mypy-protobuf

Earlier releases might work, but aren't tested

- [mypy >= v1.4.1](https://pypi.org/project/mypy) or [pyright >= 1.1.206](https://github.com/microsoft/pyright)
- [python-protobuf >= 4.25.3](https://pypi.org/project/protobuf/) - matching protoc release
- [types-protobuf >= 4.24](https://pypi.org/project/types-protobuf/) - for stubs from the google.protobuf library

### To run typecheckers on code generated with grpc plugin - you'll additionally need

Earlier releases might work, but aren't tested

- [grpcio>=1.56.2](https://pypi.org/project/grpcio/)
- [grpcio-tools>=1.56.2](https://pypi.org/project/grpcio-tools/)
- [grpc-stubs>=1.53.0.2](https://pypi.org/project/grpc-stubs/)

Other configurations may work, but are not continuously tested currently.
We would be open to expanding this list - file an issue on the issue tracker.

## Installation

The plugin can be installed with

```
pip3 install mypy-protobuf
```

To install unreleased

```
REV=main  # or whichever unreleased git rev you'd like
pip3 install git+https://github.com/nipunn1313/mypy-protobuf.git@$REV

# For older (1.x) versions of mypy protobuf - you may need
pip3 install git+https://github.com/nipunn1313/mypy-protobuf.git@$REV#subdirectory=python
```

In order to run mypy on the generated code, you'll need to install

```
pip3 install mypy>=0.910 types-protobuf>=0.1.14
```

# Usage

On posix, protoc-gen-mypy is installed to python's executable bin. Assuming that's
on your $PATH, you can run

```
protoc --python_out=output/location --mypy_out=output/location
```

Alternately, you can explicitly provide the path:

```
protoc --plugin=protoc-gen-mypy=path/to/protoc-gen-mypy --python_out=output/location --mypy_out=output/location
```

Check the version number with

```
> protoc-gen-mypy --version
```

## Implementation

The implementation of the plugin is in `mypy_protobuf/main.py`, which installs to
an executable protoc-gen-mypy. On windows it installs to `protoc-gen-mypy.exe`

## Features

See [Changelog](CHANGELOG.md) for full listing

### Bring comments from .proto files to docstrings in .pyi files

Comments in the .proto files on messages, fields, enums, enum variants, extensions, services, and methods
will appear as docstrings in .pyi files. Useful in IDEs for showing completions with comments.

### Types enum int values more strongly

Enum int values produce stubs which wrap the int values in NewType

```proto
enum MyEnum {
  HELLO = 0;
  WORLD = 1;
}
```

Will yield an [enum type wrapper](https://github.com/python/typeshed/blob/16ae4c61201cd8b96b8b22cdfb2ab9e89ba5bcf2/stubs/protobuf/google/protobuf/internal/enum_type_wrapper.pyi) whose methods type to `MyEnum.ValueType` (a `NewType(int)` rather than `int`.
This allows mypy to catch bugs where the wrong enum value is being used.

Calling code may be typed as follows.

In python >= 3.7

```python
# May need [PEP 563](https://www.python.org/dev/peps/pep-0563/) to postpone evaluation of annotations
# from __future__ import annotations  # Not needed with python>=3.11 or protobuf>=3.20.0
def f(x: MyEnum.ValueType):
    print(x)
f(MyEnum.Value("HELLO"))
```

With protobuf <= 3.20.0, for usages of cast, the type of `x` must be quoted
After protobuf >= 3.20.0 - `ValueType` exists in the python code and quotes aren't needed
until [upstream protobuf](https://github.com/protocolbuffers/protobuf/pull/8182) includes `ValueType`

```python
cast('MyEnum.ValueType', x)
```

Similarly, for type aliases with protobuf < 3.20.0, you must either quote the type or hide it behind `TYPE_CHECKING`

```python
from typing import Tuple, TYPE_CHECKING
HELLO = Tuple['MyEnum.ValueType', 'MyEnum.ValueType']
if TYPE_CHECKING:
    HELLO = Tuple[MyEnum.ValueType, MyEnum.ValueType]
```

#### Enum int impl details

mypy-protobuf autogenerates an instance of the EnumTypeWrapper as follows.

```python
class _MyEnum:
    ValueType = typing.NewType('ValueType', builtins.int)
    V: typing_extensions.TypeAlias = ValueType
class _MyEnumEnumTypeWrapper(google.protobuf.internal.enum_type_wrapper._EnumTypeWrapper[_MyEnum.ValueType], builtins.type):
    DESCRIPTOR: google.protobuf.descriptor.EnumDescriptor
    HELLO: _MyEnum.ValueType  # 0
    WORLD: _MyEnum.ValueType  # 1
class MyEnum(_MyEnum, metaclass=_MyEnumEnumTypeWrapper):
    pass

HELLO: MyEnum.ValueType  # 0
WORLD: MyEnum.ValueType  # 1
```

`_MyEnumEnumTypeWrapper` extends the EnumTypeWrapper to take/return MyEnum.ValueType rather than int
`MyEnum` is an instance of the `EnumTypeWrapper`.

- Use `_MyEnum` and of metaclass is an implementation detail to make MyEnum.ValueType a valid type w/o a circular dependency
- `V` is supported as an alias of `ValueType` for backward compatibility

### Supports generating type wrappers for fields and maps

M.proto

```proto
message M {
  uint32 user_id = 1 [(mypy_protobuf.options).casttype="mymod.UserId"];
  map<uint32, string> email_by_uid = 2 [
    (mypy_protobuf.options).keytype="path/to/mymod.UserId",
    (mypy_protobuf.options).valuetype="path/to/mymod.Email"
  ];
}
```

mymod.py

```python
UserId = NewType("UserId", int)
Email = NewType("Email", Text)
```

### `py_generic_services`

If `py_generic_services` is set in your proto file, then mypy-protobuf will
generate service stubs. If you want GRPC stubs instead - use the GRPC instructions.

### `readable_stubs`

If `readable_stubs` is set, mypy-protobuf will generate easier-to-read stubs. The downside
to this approach - is that it's possible to generate stubs which do not pass mypy - particularly
in the case of name collisions. mypy-protobuf defaults to generating stubs with fully qualified
imports and mangled global-level identifiers to defend against name collisions between global
identifiers and field names.

If you're ok with this risk, try it out!

```
protoc --python_out=output/location --mypy_out=readable_stubs:output/location
```

### `relax_strict_optional_primitives`

If you are using proto3, then primitives cannot be represented as NULL on the wire -
only as their zero value. By default mypy-protobuf types message constructors to have
non-nullable primitives (eg `int` instead of `Optional[int]`). python-protobuf itself will
internally convert None -> zero value. If you intentionally want to use this behavior,
set this flag! We recommend avoiding this, as it can lead to developer error - confusing
NULL and 0 as distinct on the wire.
However, it may be helpful when migrating existing proto2 code, where the distinction is meaningful

```
protoc --python_out=output/location --mypy_out=relax_strict_optional_primitives:output/location
```

### Output suppression

To suppress output, you can run

```
protoc --python_out=output/location --mypy_out=quiet:output/location
```

### GRPC

This plugin provides stubs generation for grpcio generated code.

```
protoc \
    --python_out=output/location \
    --mypy_out=output/location \
    --grpc_out=output/location \
    --mypy_grpc_out=output/location
```

Note that generated code for grpc will work only together with code for python and locations should be the same.
If you need stubs for grpc internal code we suggest using this package https://github.com/shabbyrobe/grpc-stubs

### Targeting python2 support

mypy-protobuf's drops support for targeting python2 with version 3.0. If you still need python2 support -

```
python3 -m pip install mypy_protobuf==2.10
protoc --python_out=output/location --mypy_out=output/location
mypy --target-version=2.7 {files}
```

## Contributing

Contributions to the implementation are welcome. Please run tests using `./run_test.sh`.
Ensure code is formatted using black.

```
pip3 install black
black .
```

## Contributors

- [@nipunn1313](https://github.com/nipunn1313)
- [@dzbarsky](https://github.com/dzbarsky)
- [@gvanrossum](https://github.com/gvanrossum)
- [@peterlvilim](https://github.com/peterlvilim)
- [@msullivan](https://github.com/msullivan)
- [@bradenaw](https://github.com/bradenaw)
- [@ilevkivskyi](https://github.com/ilevkivskyi)
- [@Ketouem](https://github.com/Ketouem)
- [@nmiculinic](https://github.com/nmiculinic)
- [@onto](https://github.com/onto)
- [@jcppkkk](https://github.com/jcppkkk)
- [@drather19](https://github.com/drather19)
- [@smessmer](https://github.com/smessmer)
- [@pcorpet](https://github.com/pcorpet)
- [@zozoens31](https://github.com/zozoens31)
- [@abhishekrb19](https://github.com/abhishekrb19)
- [@jaens](https://github.com/jaens)
- [@arussellsaw](https://github.com/arussellsaw)
- [@shabbyrobe](https://github.com/shabbyrobe)
- [@reorx](https://github.com/reorx)
- [@zifter](https://github.com/zifter)
- [@juzna](https://github.com/juzna)
- [@mikolajz](https://github.com/mikolajz)
- [@chadrik](https://github.com/chadrik)
- [@EPronovost](https://github.com/EPronovost)
- [@chrislawlor](https://github.com/chrislawlor)
- [@henribru](https://github.com/henribru)
- [@Evgenus](https://github.com/Evgenus)
- [@MHDante](https://github.com/MHDante)
- [@nelfin](https://github.com/nelfin)
- [@alkasm](https://github.com/alkasm)
- [@tarmath](https://github.com/tarmath)
- [@jaredkhan](https://github.com/jaredkhan)
- [@sodul](https://github.com/sodul)
- [@miaachan](https://github.com/miaachan)
- [@Alphadelta14](https://github.com/Alphadelta14)
- [@fergyfresh](https://github.com/fergyfresh)
- [@AlexWaygood](https://github.com/AlexWaygood)

## Licence etc.

1. License: Apache 2.0.
2. Copyright attribution: Copyright (c) 2022 Nipunn Koorapati


The problem
===========

.. image:: https://badge.fury.io/py/platformdirs.svg
   :target: https://badge.fury.io/py/platformdirs
.. image:: https://img.shields.io/pypi/pyversions/platformdirs.svg
   :target: https://pypi.python.org/pypi/platformdirs/
.. image:: https://github.com/tox-dev/platformdirs/actions/workflows/check.yaml/badge.svg
   :target: https://github.com/platformdirs/platformdirs/actions
.. image:: https://static.pepy.tech/badge/platformdirs/month
   :target: https://pepy.tech/project/platformdirs

When writing desktop application, finding the right location to store user data
and configuration varies per platform. Even for single-platform apps, there
may by plenty of nuances in figuring out the right location.

For example, if running on macOS, you should use::

    ~/Library/Application Support/<AppName>

If on Windows (at least English Win) that should be::

    C:\Documents and Settings\<User>\Application Data\Local Settings\<AppAuthor>\<AppName>

or possibly::

    C:\Documents and Settings\<User>\Application Data\<AppAuthor>\<AppName>

for `roaming profiles <https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-vista/cc766489(v=ws.10)>`_ but that is another story.

On Linux (and other Unices), according to the `XDG Basedir Spec`_, it should be::

    ~/.local/share/<AppName>

.. _XDG Basedir Spec: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html

``platformdirs`` to the rescue
==============================

This kind of thing is what the ``platformdirs`` package is for.
``platformdirs`` will help you choose an appropriate:

- user data dir (``user_data_dir``)
- user config dir (``user_config_dir``)
- user cache dir (``user_cache_dir``)
- site data dir (``site_data_dir``)
- site config dir (``site_config_dir``)
- user log dir (``user_log_dir``)
- user documents dir (``user_documents_dir``)
- user downloads dir (``user_downloads_dir``)
- user pictures dir (``user_pictures_dir``)
- user videos dir (``user_videos_dir``)
- user music dir (``user_music_dir``)
- user desktop dir (``user_desktop_dir``)
- user runtime dir (``user_runtime_dir``)

And also:

- Is slightly opinionated on the directory names used. Look for "OPINION" in
  documentation and code for when an opinion is being applied.

Example output
==============

On macOS:

.. code-block:: pycon

    >>> from platformdirs import *
    >>> appname = "SuperApp"
    >>> appauthor = "Acme"
    >>> user_data_dir(appname, appauthor)
    '/Users/trentm/Library/Application Support/SuperApp'
    >>> site_data_dir(appname, appauthor)
    '/Library/Application Support/SuperApp'
    >>> user_cache_dir(appname, appauthor)
    '/Users/trentm/Library/Caches/SuperApp'
    >>> user_log_dir(appname, appauthor)
    '/Users/trentm/Library/Logs/SuperApp'
    >>> user_documents_dir()
    '/Users/trentm/Documents'
    >>> user_downloads_dir()
    '/Users/trentm/Downloads'
    >>> user_pictures_dir()
    '/Users/trentm/Pictures'
    >>> user_videos_dir()
    '/Users/trentm/Movies'
    >>> user_music_dir()
    '/Users/trentm/Music'
    >>> user_desktop_dir()
    '/Users/trentm/Desktop'
    >>> user_runtime_dir(appname, appauthor)
    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'

On Windows:

.. code-block:: pycon

    >>> from platformdirs import *
    >>> appname = "SuperApp"
    >>> appauthor = "Acme"
    >>> user_data_dir(appname, appauthor)
    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp'
    >>> user_data_dir(appname, appauthor, roaming=True)
    'C:\\Users\\trentm\\AppData\\Roaming\\Acme\\SuperApp'
    >>> user_cache_dir(appname, appauthor)
    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Cache'
    >>> user_log_dir(appname, appauthor)
    'C:\\Users\\trentm\\AppData\\Local\\Acme\\SuperApp\\Logs'
    >>> user_documents_dir()
    'C:\\Users\\trentm\\Documents'
    >>> user_downloads_dir()
    'C:\\Users\\trentm\\Downloads'
    >>> user_pictures_dir()
    'C:\\Users\\trentm\\Pictures'
    >>> user_videos_dir()
    'C:\\Users\\trentm\\Videos'
    >>> user_music_dir()
    'C:\\Users\\trentm\\Music'
    >>> user_desktop_dir()
    'C:\\Users\\trentm\\Desktop'
    >>> user_runtime_dir(appname, appauthor)
    'C:\\Users\\trentm\\AppData\\Local\\Temp\\Acme\\SuperApp'

On Linux:

.. code-block:: pycon

    >>> from platformdirs import *
    >>> appname = "SuperApp"
    >>> appauthor = "Acme"
    >>> user_data_dir(appname, appauthor)
    '/home/trentm/.local/share/SuperApp'
    >>> site_data_dir(appname, appauthor)
    '/usr/local/share/SuperApp'
    >>> site_data_dir(appname, appauthor, multipath=True)
    '/usr/local/share/SuperApp:/usr/share/SuperApp'
    >>> user_cache_dir(appname, appauthor)
    '/home/trentm/.cache/SuperApp'
    >>> user_log_dir(appname, appauthor)
    '/home/trentm/.local/state/SuperApp/log'
    >>> user_config_dir(appname)
    '/home/trentm/.config/SuperApp'
    >>> user_documents_dir()
    '/home/trentm/Documents'
    >>> user_downloads_dir()
    '/home/trentm/Downloads'
    >>> user_pictures_dir()
    '/home/trentm/Pictures'
    >>> user_videos_dir()
    '/home/trentm/Videos'
    >>> user_music_dir()
    '/home/trentm/Music'
    >>> user_desktop_dir()
    '/home/trentm/Desktop'
    >>> user_runtime_dir(appname, appauthor)
    '/run/user/{os.getuid()}/SuperApp'
    >>> site_config_dir(appname)
    '/etc/xdg/SuperApp'
    >>> os.environ["XDG_CONFIG_DIRS"] = "/etc:/usr/local/etc"
    >>> site_config_dir(appname, multipath=True)
    '/etc/SuperApp:/usr/local/etc/SuperApp'

On Android::

    >>> from platformdirs import *
    >>> appname = "SuperApp"
    >>> appauthor = "Acme"
    >>> user_data_dir(appname, appauthor)
    '/data/data/com.myApp/files/SuperApp'
    >>> user_cache_dir(appname, appauthor)
    '/data/data/com.myApp/cache/SuperApp'
    >>> user_log_dir(appname, appauthor)
    '/data/data/com.myApp/cache/SuperApp/log'
    >>> user_config_dir(appname)
    '/data/data/com.myApp/shared_prefs/SuperApp'
    >>> user_documents_dir()
    '/storage/emulated/0/Documents'
    >>> user_downloads_dir()
    '/storage/emulated/0/Downloads'
    >>> user_pictures_dir()
    '/storage/emulated/0/Pictures'
    >>> user_videos_dir()
    '/storage/emulated/0/DCIM/Camera'
    >>> user_music_dir()
    '/storage/emulated/0/Music'
    >>> user_desktop_dir()
    '/storage/emulated/0/Desktop'
    >>> user_runtime_dir(appname, appauthor)
    '/data/data/com.myApp/cache/SuperApp/tmp'

Note: Some android apps like Termux and Pydroid are used as shells. These
apps are used by the end user to emulate Linux environment. Presence of
``SHELL`` environment variable is used by Platformdirs to differentiate
between general android apps and android apps used as shells. Shell android
apps also support ``XDG_*`` environment variables.

``PlatformDirs`` for convenience
================================

.. code-block:: pycon

    >>> from platformdirs import PlatformDirs
    >>> dirs = PlatformDirs("SuperApp", "Acme")
    >>> dirs.user_data_dir
    '/Users/trentm/Library/Application Support/SuperApp'
    >>> dirs.site_data_dir
    '/Library/Application Support/SuperApp'
    >>> dirs.user_cache_dir
    '/Users/trentm/Library/Caches/SuperApp'
    >>> dirs.user_log_dir
    '/Users/trentm/Library/Logs/SuperApp'
    >>> dirs.user_documents_dir
    '/Users/trentm/Documents'
    >>> dirs.user_downloads_dir
    '/Users/trentm/Downloads'
    >>> dirs.user_pictures_dir
    '/Users/trentm/Pictures'
    >>> dirs.user_videos_dir
    '/Users/trentm/Movies'
    >>> dirs.user_music_dir
    '/Users/trentm/Music'
    >>> dirs.user_desktop_dir
    '/Users/trentm/Desktop'
    >>> dirs.user_runtime_dir
    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp'

Per-version isolation
=====================

If you have multiple versions of your app in use that you want to be
able to run side-by-side, then you may want version-isolation for these
dirs::

    >>> from platformdirs import PlatformDirs
    >>> dirs = PlatformDirs("SuperApp", "Acme", version="1.0")
    >>> dirs.user_data_dir
    '/Users/trentm/Library/Application Support/SuperApp/1.0'
    >>> dirs.site_data_dir
    '/Library/Application Support/SuperApp/1.0'
    >>> dirs.user_cache_dir
    '/Users/trentm/Library/Caches/SuperApp/1.0'
    >>> dirs.user_log_dir
    '/Users/trentm/Library/Logs/SuperApp/1.0'
    >>> dirs.user_documents_dir
    '/Users/trentm/Documents'
    >>> dirs.user_downloads_dir
    '/Users/trentm/Downloads'
    >>> dirs.user_pictures_dir
    '/Users/trentm/Pictures'
    >>> dirs.user_videos_dir
    '/Users/trentm/Movies'
    >>> dirs.user_music_dir
    '/Users/trentm/Music'
    >>> dirs.user_desktop_dir
    '/Users/trentm/Desktop'
    >>> dirs.user_runtime_dir
    '/Users/trentm/Library/Caches/TemporaryItems/SuperApp/1.0'

Be wary of using this for configuration files though; you'll need to handle
migrating configuration files manually.

Why this Fork?
==============

This repository is a friendly fork of the wonderful work started by
`ActiveState <https://github.com/ActiveState/appdirs>`_ who created
``appdirs``, this package's ancestor.

Maintaining an open source project is no easy task, particularly
from within an organization, and the Python community is indebted
to ``appdirs`` (and to Trent Mick and Jeff Rouse in particular) for
creating an incredibly useful simple module, as evidenced by the wide
number of users it has attracted over the years.

Nonetheless, given the number of long-standing open issues
and pull requests, and no clear path towards `ensuring
that maintenance of the package would continue or grow
<https://github.com/ActiveState/appdirs/issues/79>`_, this fork was
created.

Contributions are most welcome.


# `pure_eval`

[![Build Status](https://travis-ci.org/alexmojaki/pure_eval.svg?branch=master)](https://travis-ci.org/alexmojaki/pure_eval) [![Coverage Status](https://coveralls.io/repos/github/alexmojaki/pure_eval/badge.svg?branch=master)](https://coveralls.io/github/alexmojaki/pure_eval?branch=master) [![Supports Python versions 3.7+](https://img.shields.io/pypi/pyversions/pure_eval.svg)](https://pypi.python.org/pypi/pure_eval)

This is a Python package that lets you safely evaluate certain AST nodes without triggering arbitrary code that may have unwanted side effects.

It can be installed from PyPI:

    pip install pure_eval

To demonstrate usage, suppose we have an object defined as follows:

```python
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @property
    def area(self):
        print("Calculating area...")
        return self.width * self.height

rect = Rectangle(3, 5)
```

Given the `rect` object, we want to evaluate whatever expressions we can in this source code:

```python
source = "(rect.width, rect.height, rect.area)"
```

This library works with the AST, so let's parse the source code and peek inside:

```python
import ast

tree = ast.parse(source)
the_tuple = tree.body[0].value
for node in the_tuple.elts:
    print(ast.dump(node))
```

Output:

```python
Attribute(value=Name(id='rect', ctx=Load()), attr='width', ctx=Load())
Attribute(value=Name(id='rect', ctx=Load()), attr='height', ctx=Load())
Attribute(value=Name(id='rect', ctx=Load()), attr='area', ctx=Load())
```

Now to actually use the library. First construct an Evaluator:

```python
from pure_eval import Evaluator

evaluator = Evaluator({"rect": rect})
```

The argument to `Evaluator` should be a mapping from variable names to their values. Or if you have access to the stack frame where `rect` is defined, you can instead use:

```python
evaluator = Evaluator.from_frame(frame)
```

Now to evaluate some nodes, using `evaluator[node]`:

```python
print("rect.width:", evaluator[the_tuple.elts[0]])
print("rect:", evaluator[the_tuple.elts[0].value])
```

Output:

```
rect.width: 3
rect: <__main__.Rectangle object at 0x105b0dd30>
```

OK, but you could have done the same thing with `eval`. The useful part is that it will refuse to evaluate the property `rect.area` because that would trigger unknown code. If we try, it'll raise a `CannotEval` exception.

```python
from pure_eval import CannotEval

try:
    print("rect.area:", evaluator[the_tuple.elts[2]])  # fails
except CannotEval as e:
    print(e)  # prints CannotEval
```

To find all the expressions that can be evaluated in a tree:

```python
for node, value in evaluator.find_expressions(tree):
    print(ast.dump(node), value)
```

Output:

```python
Attribute(value=Name(id='rect', ctx=Load()), attr='width', ctx=Load()) 3
Attribute(value=Name(id='rect', ctx=Load()), attr='height', ctx=Load()) 5
Name(id='rect', ctx=Load()) <__main__.Rectangle object at 0x105568d30>
Name(id='rect', ctx=Load()) <__main__.Rectangle object at 0x105568d30>
Name(id='rect', ctx=Load()) <__main__.Rectangle object at 0x105568d30>
```

Note that this includes `rect` three times, once for each appearance in the source code. Since all these nodes are equivalent, we can group them together:

```python
from pure_eval import group_expressions

for nodes, values in group_expressions(evaluator.find_expressions(tree)):
    print(len(nodes), "nodes with value:", values)
```

Output:

```
1 nodes with value: 3
1 nodes with value: 5
3 nodes with value: <__main__.Rectangle object at 0x10d374d30>
```

If we want to list all the expressions in a tree, we may want to filter out certain expressions whose values are obvious. For example, suppose we have a function `foo`:

```python
def foo():
    pass
```

If we refer to `foo` by its name as usual, then that's not interesting:

```python
from pure_eval import is_expression_interesting

node = ast.parse('foo').body[0].value
print(ast.dump(node))
print(is_expression_interesting(node, foo))
```

Output:

```python
Name(id='foo', ctx=Load())
False
```

But if we refer to it by a different name, then it's interesting:

```python
node = ast.parse('bar').body[0].value
print(ast.dump(node))
print(is_expression_interesting(node, foo))
```

Output:

```python
Name(id='bar', ctx=Load())
True
```

In general `is_expression_interesting` returns False for the following values:
- Literals (e.g. `123`, `'abc'`, `[1, 2, 3]`, `{'a': (), 'b': ([1, 2], [3])}`)
- Variables or attributes whose name is equal to the value's `__name__`, such as `foo` above or `self.foo` if it was a method.
- Builtins (e.g. `len`) referred to by their usual name.

To make things easier, you can combine finding expressions, grouping them, and filtering out the obvious ones with:

```python
evaluator.interesting_expressions_grouped(root)
```

To get the source code of an AST node, I recommend [asttokens](https://github.com/gristlabs/asttokens).

Here's a complete example that brings it all together:

```python
from asttokens import ASTTokens
from pure_eval import Evaluator

source = """
x = 1
d = {x: 2}
y = d[x]
"""

names = {}
exec(source, names)
atok = ASTTokens(source, parse=True)
for nodes, value in Evaluator(names).interesting_expressions_grouped(atok.tree):
    print(atok.get_text(nodes[0]), "=", value)
```

Output:

```python
x = 1
d = {1: 2}
y = 2
d[x] = 2
```


.. -*- coding: utf-8 -*-
.. :Project:   python-rapidjson -- Introduction
.. :Author:    Ken Robbins <ken@kenrobbins.com>
.. :License:   MIT License
.. :Copyright: © 2015 Ken Robbins
.. :Copyright: © 2016, 2017, 2018, 2020, 2022 Lele Gaifax
..

==================
 python-rapidjson
==================

Python wrapper around RapidJSON
===============================

:Authors: Ken Robbins <ken@kenrobbins.com>; Lele Gaifax <lele@metapensiero.it>
:License: `MIT License`__
:Status: |build| |doc|

__ https://raw.githubusercontent.com/python-rapidjson/python-rapidjson/master/LICENSE
.. |build| image:: https://travis-ci.org/python-rapidjson/python-rapidjson.svg?branch=master
   :target: https://travis-ci.org/python-rapidjson/python-rapidjson
   :alt: Build status
.. |doc| image:: https://readthedocs.org/projects/python-rapidjson/badge/?version=latest
   :target: https://readthedocs.org/projects/python-rapidjson/builds/
   :alt: Documentation status

RapidJSON_ is an extremely fast C++ JSON parser and serialization library: this module
wraps it into a Python 3 extension, exposing its serialization/deserialization (to/from
either ``bytes``, ``str`` or *file-like* instances) and `JSON Schema`__ validation
capabilities.

Latest version documentation is automatically rendered by `Read the Docs`__.

__ http://json-schema.org/documentation.html
__ https://python-rapidjson.readthedocs.io/en/latest/

Getting Started
---------------

First install ``python-rapidjson``:

.. code-block:: bash

    $ pip install python-rapidjson

or, if you prefer `Conda`__:

.. code-block:: bash

    $ conda install -c conda-forge python-rapidjson

__ https://conda.io/docs/

Basic usage looks like this:

.. code-block:: python

    >>> import rapidjson
    >>> data = {'foo': 100, 'bar': 'baz'}
    >>> rapidjson.dumps(data)
    '{"foo":100,"bar":"baz"}'
    >>> rapidjson.loads('{"bar":"baz","foo":100}')
    {'bar': 'baz', 'foo': 100}
    >>>
    >>> class Stream:
    ...   def write(self, data):
    ...      print("Chunk:", data)
    ...
    >>> rapidjson.dump(data, Stream(), chunk_size=5)
    Chunk: b'{"foo'
    Chunk: b'":100'
    Chunk: b',"bar'
    Chunk: b'":"ba'
    Chunk: b'z"}'

Development
-----------

If you want to install the development version (maybe to contribute fixes or
enhancements) you may clone the repository:

.. code-block:: bash

    $ git clone --recursive https://github.com/python-rapidjson/python-rapidjson.git

.. note:: The ``--recursive`` option is needed because we use a *submodule* to
          include RapidJSON_ sources. Alternatively you can do a plain
          ``clone`` immediately followed by a ``git submodule update --init``.

          Alternatively, if you already have (a *compatible* version of)
          RapidJSON includes around, you can compile the module specifying
          their location with the option ``--rj-include-dir``, for example:

          .. code-block:: shell

             $ python3 setup.py build --rj-include-dir=/usr/include/rapidjson

A set of makefiles implement most common operations, such as *build*, *check*
and *release*; see ``make help`` output for a list of available targets.

Performance
-----------

``python-rapidjson`` tries to be as performant as possible while staying
compatible with the ``json`` module.

See the `this section`__ in the documentation for a comparison with other JSON libraries.

__ https://python-rapidjson.readthedocs.io/en/latest/benchmarks.html

Incompatibility
---------------

Although we tried to implement an API similar to the standard library ``json``, being a
strict *drop-in* replacement in not our goal and we have decided to depart from there in
some aspects. See `this section`__ in the documentation for further details.

__ https://python-rapidjson.readthedocs.io/en/latest/quickstart.html#incompatibilities

.. _RapidJSON: http://rapidjson.org/