# Packages

A package is a git repository of Ant files with an `ant.json` at its root. Its author publishes a
version by pushing a tag, and your program imports its libraries as it imports its own. `ant`
fetches a package with `git` the first time a program needs it. There is no registry and no account,
a version is never a range, and fetching a package runs none of its code.

The path of a package is its host and repository: for a repository on GitHub,
`github.com/owner/name`. This chapter uses one small package, `example.com/slug`, which turns a
title into the part of an address that names a page. It is made up for these pages, and no
repository is at that address.

## A package in a script

A script with no project file, an `ant.json` in its directory or above, names the package and its
version in the `import`:

```ant
import "example.com/slug@1.2.0" Slug

println(Slug.make("Hello, Ant"))
```

```text
hello-ant
```

The version after `@` is the tag `v1.2.0` of the repository. The first run fetches it and says so on
standard error, `ant: fetching example.com/slug 1.2.0`. Later runs read it from the
[store](https://ant-lang.org/docs/guide/packages.md#fetching-and-the-store) and need no network.

- The import above names the package's main file. A file after the version names another library of
  the package: `import "example.com/slug@1.2.0/words.ant" { words }`.
- The version is exact. The script runs the version it writes, so two imports of one major version
  of a package write the same version.
- The script is complete in one file. Copy it to another machine that has `git`, and the first run
  there fetches the package.

Once a program grows past a few files, give it a project file.

## A project

A project lists its packages once, in a file named `ant.json`, and gives each a short name.
[`ant add`](https://ant-lang.org/docs/tools/add.md) writes the file:

```sh
ant add example.com/slug                # under the name slug
ant add slug1:example.com/slug@1.2.0    # another major version, under its own name
ant add --dev example.com/golden        # for test files only
```

```json [blog/ant.json]
{
  "dependencies": {
    "slug": "example.com/slug@2.0.0",
    "slug1": "example.com/slug@1.2.0"
  },
  "devDependencies": {
    "golden": "example.com/golden@0.3.0"
  }
}
```

For a package the project does not have yet, `ant add` without a version takes the highest release
the repository has, here `2.0.0`. It names the entry by the last segment of the path unless you
write `name:` in front. Every file of the project now imports the package by that name:

```ant [blog/main.ant]
import "slug" Slug

println("/posts/${Slug.make("Crème brûlée")}")
```

```text
/posts/crème-brûlée
```

`ant add` also writes `ant.lock` beside `ant.json`. [The lock](https://ant-lang.org/docs/guide/packages.md#the-lock) holds the version and the
hash of every package the project uses. Commit both files:

```text
blog/
  ant.json     the packages the project asks for
  ant.lock     the versions that were selected, each with its hash
  main.ant
```

The project file of a program is the `ant.json` in the directory of the script you run, or in the
nearest directory above it. So a script in `blog/tools/` reads the same names as `blog/main.ant`.

A program with a project file writes its versions there and nowhere else. An import that pins a
version, as in the script above, is an error in a project: the program does not load, and the
message names `ant add`. So an `ant.json` makes one project of every script in its directory and
below, and a script there that pins a version stops loading until it imports by name.

## Import paths

The text before the first `/` of an import path says what the path names:

| Path                                           | Names                                          |
| ---------------------------------------------- | ---------------------------------------------- |
| `./titles.ant`, `../lib/titles.ant`            | A file, relative to the importing file         |
| `slug`                                         | The main file of the dependency named `slug`   |
| `slug/words.ant`                               | That file of the dependency                    |
| `example.com/slug@1.2.0`, or with `/words.ant` | A pinned package, in a program with no project |

Anything else is an error, and the program does not load. The path of your own file always starts
with `./` or `../`, so `import "titles.ant"` is an error whose message offers `"./titles.ant"`.

A library of the project that uses two files of the package:

```ant [blog/titles.ant]
import "slug" Slug
import "slug/words.ant" { words }

export func link(title: string): string {
  "/posts/${Slug.make(title)}"
}

export func isShort(title: string): bool {
  words(title).length() <= 3
}
```

A name always means an entry of `ant.json`. It starts with a letter and holds letters, digits, `_`,
and `-`, so a name never looks like a file path or a host.

## Versions

A version is three numbers, such as `1.2.0`, with an optional prerelease, such as `1.2.0-rc.1`. The
tag that publishes it is `v` and the version.

Versions belong to **lines**. The line of a version is its major number, so `1.2.0` and `1.9.3` are
both line `1`. Below `1.0` the line is `0.` and the minor number, so `0.3.1` is line `0.3` and
`0.4.0` is line `0.4`. Versions of one line are expected to be compatible: a new version in the line
adds and fixes, and a change that breaks callers starts a new line.

An entry in `ant.json` asks for at least that version in its line. The packages you use ask for
their own packages the same way, and `ant` selects, for each package and line, the highest version
that anyone asked for:

```text
your project   asks for   text 1.2.0, feed 0.4.1
feed           asks for   text 1.4.0
text has       1.2.0, 1.4.0, 1.9.0, 2.0.0

selected       text 1.4.0, feed 0.4.1
```

- Nobody asked for `1.9.0`, so it is not used. A version enters your program only when someone
  writes it in an `ant.json`, so a release published an hour ago cannot arrive by itself.
- The result depends only on the `ant.json` files. Two machines select the same versions.
- [`ant update`](https://ant-lang.org/docs/tools/update.md) raises your own entries to the highest release of their lines.
  It never moves an entry to another line; `ant add example.com/slug@2.0.0` does.
- To raise a package that only another package asks for, as for a fix, add it to your own
  `dependencies`.

### Two lines side by side

Two lines of one package are two packages. Give each a name, and a program uses both:

```ant [blog/compare.ant]
import "slug" Slug
import "slug1" Slug1

println(Slug.make("Crème brûlée"))
println(Slug1.make("Crème brûlée"))
```

```text
crème-brûlée
cr-me-br-l-e
```

Line `2` of this package keeps letters such as `è` and `û`, and line `1` keeps ASCII letters only. A
project moves to a new line one file at a time this way. The two share nothing: a type of one line
is not the type of the same name in the other.

## The lock

`ant.lock` lists every package the project uses, its own and those its packages bring in, each with
the version that was selected and the hash of its files:

```text [blog/ant.lock]
# ant lock v1
# requires 913e71ef4143b30c4e110f031c5ad2328a68d2d3bd3995077456fd8a6daeeac9
example.com/golden 0.3.0 h1:xH2rvFwGyfHti8FBi0YgZx41yGctjM8EV8Yzy3veWJg=
example.com/slug 1.2.0 h1:0BWDbN17nND+b0dWie2+jW/UizrNLdM8u/0SkI94XcM=
example.com/slug 2.0.0 h1:Jglk0kfOownuI6LhhbAdjQkw2yxy3nTKAgjgD7V3I7M=
```

- **Commit it.** With the lock, every machine runs the same files. `ant` refuses a package whose
  files do not match the hash in the lock, so a tag that someone moved cannot change your program.
- **Four commands write it:** `ant add`, [`ant remove`](https://ant-lang.org/docs/tools/remove.md), `ant update`, and
  [`ant lock`](https://ant-lang.org/docs/tools/lock.md). `ant run`, `ant check`, `ant test`, and your editor read it and
  never change it.
- **It follows `ant.json`.** The `requires` line is a digest of the paths and versions in
  `ant.json`. Change a path or a version by hand and the lock is out of date. A program that imports
  a package then stops before it runs, with exit status 2 and a message that names the fix:

  ```text
  ant.lock: the lock is out of date: the requirements changed since it was written; run ant lock, which selects again [missing-module]
  ```

- **Settle a merge conflict** in the lock by keeping the lines of both sides, without git's conflict
  markers, and running `ant lock`.

A program of the project that imports no package runs whatever state the lock is in.

## Dev dependencies

A package that only your tests use goes under `devDependencies`, with `ant add --dev`. Only a test
file can import it:

```ant [blog/titles_test.ant]
import "golden" Golden
import "./titles.ant" { isShort, link }

test "link" {
  assert(Golden.diff(link("Hello, Ant"), "/posts/hello-ant").isEmpty())
}

test "isShort" {
  assert(isShort("Hello, Ant"))
}
```

```text
ok    2 passed (0.00s)
```

`ant run` fetches only the packages a program imports, so a machine that runs the program never
fetches `golden`. `ant test` fetches it when a test file needs it.

A test file reads the private names of your own files, as [Modules](https://ant-lang.org/docs/guide/modules.md) shows. The private
names of a package stay private to the package.

## Locking a script

A script with pinned imports runs with no lock: its source says which versions it runs. Nothing
checks the files that its first fetch brings, though. To record their hashes, write a lock for the
script, here `slugify.ant`:

```sh
ant lock slugify.ant
```

This writes `slugify.ant.lock` beside the script. While that file is there, `ant` takes every
package of the script under the hash it gives, and the script stops loading when you change a pin
without running `ant lock slugify.ant` again.

When a package asks for a higher version of something your script pins, the script does not load.
The error at the import names the version to write:

```text
slugify.ant:1:1: cannot import "example.com/slug@1.2.0": example.com/feed 0.4.1 requires example.com/slug 1.4.0: write @1.4.0 [import]
```

## Writing a package

A package is a repository with an `ant.json` at its root. `main` names the library that
`import "slug"` reads, and `{}` alone is a complete `ant.json`:

```json [slug/ant.json]
{
  "main": "slug.ant"
}
```

```ant [slug/slug.ant]
//! Slug makes the part of an address that names a page from the page's title.

import "./words.ant" { words }

// make returns the words of title in lower case, joined by "-".
export func make(title: string): string {
  words(title) | String.join("-")
}
```

```ant [slug/words.ant]
//! Words splits a text into its words.

// words returns the runs of ASCII letters and digits in text, in lower case.
export func words(text: string): Array[string] {
  Regex.findAll(/[a-z0-9]+/, text.toLower()) | Array.map({ x.text })
}
```

Publish a version by pushing a tag:

```sh
git tag v1.2.0
git push origin v1.2.0
```

| Field             | Value                                                                               |
| ----------------- | ----------------------------------------------------------------------------------- |
| `main`            | The library that `import "name"` reads, as a path from the package root             |
| `bin`             | Command names mapped to script files. `ant` checks its form and does not run it yet |
| `dependencies`    | Names mapped to `path@version`                                                      |
| `devDependencies` | The same, for test files                                                            |

These four are all the fields. `ant` rejects any other field in the `ant.json` of your own project.

- **Every library is public.** A user imports any library of the package by its path, such as
  `slug/words.ant`, so `export` is the line between what you offer and what you keep.
- **Inside the package,** a file imports the package's own files by relative path and the package's
  dependencies by the names in its own `ant.json`. So one name may mean different packages in your
  package and in the project that uses it. A relative path cannot leave the package.
- **Your `ant.lock` is yours alone.** A project that uses your package reads the `dependencies` of
  your `ant.json`, as minimums, and never your lock.
- **`devDependencies` are yours alone.** A project that uses your package never reads or fetches
  them.
- **Keep a line compatible.** Users of line `1` get your next `1.x` release when anyone in their
  program asks for it. Start line `2` for a change that breaks them. They can then use both lines
  while they move.
- **Never move a tag.** A lock that names the version refuses the new files. On a machine that holds
  both, a script with no lock stops loading until `ant lock` writes one.
- **The version is the tag.** `ant.json` does not hold it.

## Fetching and the store

`ant` fetches a package with the `git` command, from `https://` and the package path. It works the
same with a forge such as GitHub, a company's own server, or a plain git server.

- **Private repositories** use what `git` on the machine already uses: a credential helper, a
  `.netrc`, or SSH in place of HTTPS through git's `url.<base>.insteadOf` setting. `ant` asks for no
  password and keeps none.
- **Only the committed files.** `ant` reads the files that the tag's commit holds. It checks nothing
  out, fetches no submodule, and runs no code of the package.
- **`git` is needed to fetch,** and not to run. A machine whose store holds the packages of a
  program runs it with no `git` and no network.

Fetched packages live in the store: the directory `ANT_STORE` names, or `ant/store` under the
directory [`Os.cacheDir`](https://ant-lang.org/docs/lib/Os/cacheDir.md) returns. Each version has a directory there, named
by its path, version, and hash, and programs read it in place. A project has no directory of
packages of its own.

- The files of the store are read-only, so an editor that opens a package cannot change it for every
  project.
- Nothing removes a package from the store. Delete the whole directory when you want the space back;
  the next run fetches what it needs.

Your editor and [`ant code`](https://ant-lang.org/docs/tools/code.md) read the store and never fetch. For a package the
store lacks, they report an error that names `ant check`, which fetches it.

## Coming from other languages

- **No registry.** A package is its repository, and its name in the world is the repository's path.
  Nothing is published anywhere but the git server, and no service sees what you fetch but that
  server.
- **No version ranges.** There is no `^1.2.0`. An entry is a minimum in its line, and the highest
  version anyone asked for is used, as Go modules select. A new release reaches your project only
  when an `ant.json` asks for it: yours after `ant update`, or that of a package you add or raise.
- **No `node_modules` and no install step.** `ant run` fetches what the program imports into one
  store that all your projects share.
- **No install scripts.** Fetching writes files and runs nothing.
- **A major version is a name, not a path.** Go writes `/v2` into the import path; Ant gives the
  second line a name of its own in `ant.json`, such as `slug1`.
- **The lock is required.** In a project with dependencies and no `ant.lock`, a program that imports
  a package does not run; `ant lock` writes the lock.

## See also

[Modules](https://ant-lang.org/docs/guide/modules.md), [Testing](https://ant-lang.org/docs/guide/testing.md), [`import`](https://ant-lang.org/docs/language/keywords/import.md),
[`ant add`](https://ant-lang.org/docs/tools/add.md), [`ant remove`](https://ant-lang.org/docs/tools/remove.md),
[`ant update`](https://ant-lang.org/docs/tools/update.md), [`ant lock`](https://ant-lang.org/docs/tools/lock.md), [`ant run`](https://ant-lang.org/docs/tools/run.md),
[`ant check`](https://ant-lang.org/docs/tools/check.md), [`ant test`](https://ant-lang.org/docs/tools/test.md)
