Metadata-Version: 2.4
Name: jira-project-backup-restore
Version: 1.5.1
Summary: Backup and restore individual Jira Cloud projects via REST API
Author-email: David Malko <davidmalko87@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/davidmalko87/jira-project-backup-restore
Project-URL: Repository, https://github.com/davidmalko87/jira-project-backup-restore
Project-URL: Changelog, https://github.com/davidmalko87/jira-project-backup-restore/blob/master/CHANGELOG.md
Project-URL: Bug Tracker, https://github.com/davidmalko87/jira-project-backup-restore/issues
Keywords: jira,backup,restore,atlassian,jira-cloud,atlassian-cloud,jira-migration,jira-rest-api,project-backup,csv-export
Classifier: Development Status :: 5 - Production/Stable
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: System :: Archiving :: Backup
Classifier: Topic :: Utilities
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28
Requires-Dist: python-dotenv>=1.0
Provides-Extra: test
Requires-Dist: pytest>=7.0; extra == "test"
Dynamic: license-file

# Jira Project Backup & Restore

[![CI](https://github.com/davidmalko87/jira-project-backup-restore/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/davidmalko87/jira-project-backup-restore/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/jira-project-backup-restore.svg)](https://pypi.org/project/jira-project-backup-restore/)
[![PyPI downloads](https://img.shields.io/pypi/dm/jira-project-backup-restore.svg)](https://pypi.org/project/jira-project-backup-restore/)
[![Python](https://img.shields.io/pypi/pyversions/jira-project-backup-restore.svg?logo=python&logoColor=white)](https://pypi.org/project/jira-project-backup-restore/)
[![Jira Cloud](https://img.shields.io/badge/Jira-Cloud-0052CC.svg?logo=jira&logoColor=white)](https://www.atlassian.com/software/jira)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/davidmalko87/jira-project-backup-restore/blob/master/LICENSE)
![Platform](https://img.shields.io/badge/platform-Windows%20%7C%20macOS%20%7C%20Linux-lightgrey.svg)
[![Round-trip](https://img.shields.io/badge/round--trip-verified-success.svg)](#-round-trip-verified)
[![Last commit](https://img.shields.io/github/last-commit/davidmalko87/jira-project-backup-restore.svg)](https://github.com/davidmalko87/jira-project-backup-restore/commits/master)
[![GitHub issues](https://img.shields.io/github/issues/davidmalko87/jira-project-backup-restore.svg)](https://github.com/davidmalko87/jira-project-backup-restore/issues)

Backup and restore individual **Jira Cloud projects** via REST API. Backups cover issues, comments, worklogs, attachments, boards, and sprints; a restore recreates issues, links, comments, worklogs, and attachments in a target project. Resumable restore, with an interactive menu and CLI mode.

---

## Why?

Jira Cloud has no built-in per-project backup/restore. The only native option was the full-instance Backup Manager, which Atlassian [deprecated in March 2026](https://developer.atlassian.com/cloud/jira/platform/changelog/). This tool fills the gap using standard REST API v3 endpoints.

---

## Features

| Feature | Description |
|---|---|
| **Full project backup** | Metadata, components, versions, roles, issues (all fields + changelog), worklogs, attachments, agile boards, sprints |
| **5-phase restore** (+ opt-in phase 6) | Issues (epics first, subtasks last), links, comments, worklogs, attachments; opt-in phase 6 restores statuses |
| **Multi-project** | Backup dozens of projects in a single run |
| **Skip existing** | `--skip-existing` skips projects that already have a complete backup |
| **Auto-cleanup** | Before a backup, that project's `<KEY>_*` folders without a `manifest.json` are deleted. A multi-project run deletes **every** folder in `BACKUP_ROOT` that has no `manifest.json`, not only backup folders — keep `BACKUP_ROOT` for backups only |
| **Resumable restore** | Safely re-run an interrupted restore — already-processed items are skipped. An interrupted backup is not resumed: the next run deletes it and starts over |
| **Memory efficient** | Issues stream directly to disk during backup — CLI `--backup` handles 18 000+ issues on a 1 GB host without OOM. Restore, CSV export, and the menu's backup summaries and **Inspect backup details** load the whole `issues.json` into memory |
| **Verified backups** | Detects silent truncation (count check), records SHA-256 checksums, and validates on demand |
| **Dry-run mode** | Preview restore actions without writing anything to Jira — read-only lookups (user search, existing attachments) still call the API |
| **Rate-limit aware** | Exponential backoff with `429 / Retry-After` detection |
| **CSV export** | Export backup data to CSV files for reporting, auditing, and sharing |
| **Backup inspection** | Detailed breakdown of issue types, statuses, priorities, and assignees |
| **Connection test** | Pre-flight check: authentication, project access, and server info |
| **Interactive menu** | Guided workflow with organised sections and post-operation summaries |
| **CLI mode** | `--backup` / `--restore` / `--export-csv` / `--validate` (plus `--env`, `--with-statuses`) for scripted or cron use |

---

## Quick Start

### 1. Install

**Via PyPI (recommended)** — provides the `jira-backup` command:

```bash
pip install jira-project-backup-restore
```

**Or as an isolated app with [pipx](https://pipx.pypa.io/)** — keeps its dependencies out of your global Python:

```bash
pipx install jira-project-backup-restore
```

**Upgrade:**

```bash
pip install -U jira-project-backup-restore    # pipx: pipx upgrade jira-project-backup-restore
```

**Or clone and run from source** (development):

```bash
git clone https://github.com/davidmalko87/jira-project-backup-restore.git
cd jira-project-backup-restore
pip install -r requirements.txt
python main.py --help                         # same flags as jira-backup
```

> **Where files live:** `jira-backup` reads `.env` from the folder you run it from (or the file given with `--env /abs/path/.env`), and needs that file even for `--validate` and `--export-csv`. Backups and a `jira_tool_<timestamp>.log` for every run go to `BACKUP_ROOT` (default `./backups`), which is resolved against the folder you run from, not the `.env` location — for cron, `cd` into a dedicated folder first, or pass an absolute `--env` path and set an absolute `BACKUP_ROOT` (`~` is not expanded). A clone behaves the same with `python main.py`.

### 2. Configure

In the folder you will run `jira-backup` from, create a file named `.env` with your Jira Cloud credentials (`.env.example` is not included in the PyPI package):

```ini
JIRA_URL=https://your-domain.atlassian.net
JIRA_EMAIL=you@example.com
JIRA_API_TOKEN=your-api-token
```

> Generate an API token at [id.atlassian.com/manage-api-tokens](https://id.atlassian.com/manage-api-tokens)

Optional settings are listed in the [Configuration Reference](#configuration-reference). To start from the full commented template instead:

```bash
curl -o .env https://raw.githubusercontent.com/davidmalko87/jira-project-backup-restore/master/.env.example
cp .env.example .env                          # from a clone
```

### 3. Run

**Interactive menu:**

```bash
jira-backup --help                            # list all flags
jira-backup                                   # start the interactive menu
jira-backup --env /path/to/jira-backup/.env   # same, with a .env from another folder
```

From a clone, use `python main.py` in place of `jira-backup` — the flags are identical.

```
==================================================
  Jira Backup & Restore Tool v1.5.1
==================================================
  Instance : https://your-domain.atlassian.net
  Auth     : API Token
  Backups  : ./backups

  --- Backup & Restore ---
  1) Backup project(s)
  2) Restore project from backup

  --- Browse & Analyze ---
  3) List existing backups
  4) Validate backup integrity
  5) Upload attachments only
  6) Export backup to CSV
  7) Inspect backup details

  --- Settings & Tools ---
  8) Test Jira connection
  9) Show current configuration
  10) Cleanup incomplete backups
  0) Exit
```

**CLI — backup:**

```bash
jira-backup --backup PROJ
jira-backup --backup PROJ1,PROJ2
jira-backup --backup PROJ1,PROJ2 --skip-existing
cd /srv/jira-backup && jira-backup --backup PROJ   # cron: run from the folder that holds .env
```

**CLI — restore:**

```bash
jira-backup --restore backups/PROJ_20260322_143000 --target NEWPROJ
jira-backup --restore backups/PROJ_20260322_143000 --target NEWPROJ --dry-run         # preview, no writes
jira-backup --restore backups/PROJ_20260322_143000 --target NEWPROJ --with-statuses   # also run phase 6
```

**CLI — export to CSV:**

```bash
jira-backup --export-csv backups/PROJ_20260322_143000                          # writes <backup>/csv_export/
jira-backup --export-csv backups/PROJ_20260322_143000 --output-dir /tmp/report
```

**CLI — validate a backup** (exit code 0 = OK, 1 = backup folder, `manifest.json` or a valid `.env` missing, 2 = problems found; for scripts/cron):

```bash
jira-backup --validate backups/PROJ_20260322_143000
```

---

## What Gets Backed Up

| File | Contents |
|---|---|
| `project_meta.json` | Project config — name, lead, category |
| `components.json` | All project components |
| `versions.json` | All fix versions |
| `roles.json` | Project role names and their API URLs (no member lists) |
| `issues.json` | All issues — every field, changelog history |
| `worklogs/worklogs.json` | Time tracking entries per issue |
| `attachments/<KEY>/` | Binary attachment files, streamed to disk |
| `boards.json` | Agile board list |
| `board_<id>_config.json` | Board columns and swimlanes |
| `board_<id>_sprints.json` | Sprint history |
| `manifest.json` | File index, SHA-256 checksums, completeness counts, and a `complete` flag |

---

## Restore Phases

Each phase is resumable via `restore_progress.json`. Phases can be picked individually in the interactive menu; the CLI runs phases 1–5, plus phase 6 with `--with-statuses`:

| Phase | What happens | Endpoint |
|---|---|---|
| 1 | Create issues — epics first, then regular, then subtasks | `POST /rest/api/3/issue` |
| 2 | Restore issue links (outward only, no duplicates) | `POST /rest/api/3/issueLink` |
| 3 | Add comments — original author and date prepended as text | `POST /rest/api/3/issue/{key}/comment` |
| 4 | Add worklogs — original author prepended as text | `POST /rest/api/3/issue/{key}/worklog` |
| 5 | Upload attachments — skips duplicates by filename | `POST /rest/api/3/issue/{key}/attachments` |
| 6 | **Restore statuses** (opt-in, best-effort) — single workflow transition to the original status | `POST /rest/api/3/issue/{key}/transitions` |

Phases 1–5 run by default. Phase 6 is **opt-in** (it fires workflow rules and notifications): enable it with `--with-statuses` on the CLI, or by entering `1,2,3,4,5,6` in the interactive phase prompt (entering `6` alone runs only phase 6).

Restore state is saved inside the backup directory: `key_mapping.json` (old→new issue keys), `restore_progress.json`, and `user_cache.json`.

**What a restore recreates:** the target project must already exist. Each new issue gets its summary, issue type, description, labels, priority, reporter/assignee (when the email exists in the target), components and fix versions (matched by name, so they must already exist in the target project), and — for sub-tasks only — its parent. Custom fields, due dates, sprint membership, the parent epic of stories/tasks/bugs, and boards and sprints (backup-only) are not restored as fields. Every new issue also gets a `--- Backup Metadata ---` comment that records its original key, status, people, dates, due date, sprint, and epic link as text. Links to issues outside the backup are skipped.

---

## ✅ Round-trip Verified

The backup→restore round-trip has been **proven end-to-end against a live Jira Cloud site**: a project was backed up, restored into a fresh project, and diffed via the API — **issue count, types, sub-task parents, ADF bodies, labels, links (no duplicates), comments, worklogs, and attachment bytes (SHA-256) all matched**. A backup is only proven once it has been restored end-to-end and verified; structural checks alone are necessary but not sufficient.

---

## Known Limitations

These are Jira Cloud REST API constraints — not tool limitations:

| Data | Status | Notes |
|---|---|---|
| Timestamps (created/updated) | Not restorable | Cloud API blocks setting these fields |
| Changelog / history | Backup only | No write endpoint exists |
| Comment author | Text attribution | `[Originally by Name on Date]` prepended; original ADF body preserved |
| Worklog author | Text attribution | `[Originally logged by Name]` prepended; original ADF comment preserved |
| Reporter / Assignee | Conditional | Restored only if the user's email exists in the target instance |
| Issue status | Best-effort (opt-in) | Phase 6 restores it via a single workflow transition; statuses needing a multi-step path or a required-field screen stay at the project default |
| Issue keys (e.g. `KEY-123`) | Reassigned | Cloud assigns new keys; old→new mapping is saved |

---

## Project Structure

```
jira-project-backup-restore/
├── main.py                   # Source-checkout shim — same CLI as jira-backup
├── pyproject.toml            # Package metadata + jira-backup console script
├── .env.example              # Configuration template (not in the PyPI package)
├── requirements.txt          # Python dependencies
├── CHANGELOG.md
├── CONTRIBUTING.md
├── LICENSE
├── .github/                  # CI, PyPI publish workflow, issue/PR templates
│
├── jira_tool/
│   ├── __init__.py           # Package version (__version__)
│   ├── config.py             # .env loader and validation
│   ├── auth.py               # Session builder (API token / cookie auth)
│   ├── api_client.py         # HTTP client with retry and rate-limit handling
│   ├── backup.py             # BackupManager — orchestrates full project backup
│   ├── restore.py            # RestoreManager — 5-phase restore + opt-in phase 6
│   ├── export.py             # CSV export and backup statistics
│   ├── attachments.py        # Standalone attachment uploader
│   ├── adf.py                # Atlassian Document Format helpers
│   ├── progress.py           # Resumability tracker
│   ├── utils.py              # Logging, JSON I/O, utilities
│   ├── cli.py                # argparse flags + jira-backup console-script entry point
│   └── menu.py               # Interactive CLI menu
│
├── tests/                    # pytest suite
│
└── backups/                  # Default BACKUP_ROOT, relative to the current folder (gitignored)
    ├── jira_tool_20260322_143000.log   # One log file per run
    └── PROJ_20260322_143000/
        ├── manifest.json     # Completion marker + file index
        ├── issues.json
        ├── attachments/
        ├── key_mapping.json       # Written by restore: old → new issue keys
        ├── restore_progress.json  # Written by restore: completed phases/items
        ├── user_cache.json        # Written by restore: email → account ID lookups
        └── ...
```

---

## Configuration Reference

All settings live in `.env` (see [Configure](#2-configure)). Variables already exported in your shell take precedence over the values in `.env`, but the file itself must still exist:

| Variable | Required | Default | Description |
|---|---|---|---|
| `JIRA_URL` | Yes | — | Jira Cloud base URL (no trailing slash) |
| `JIRA_EMAIL` | Yes* | — | Account email for API token auth |
| `JIRA_API_TOKEN` | Yes* | — | API token — [generate here](https://id.atlassian.com/manage-api-tokens) |
| `JIRA_COOKIE_HEADER` | Alt* | — | Full `Cookie:` header value for SSO auth |
| `JIRA_VERIFY_SSL` | No | `true` | Set `false` to skip SSL verification |
| `BACKUP_ROOT` | No | `./backups` | Directory for backups and run logs; a relative path is resolved against the current folder (`~` is not expanded). Use a folder dedicated to backups — see **Auto-cleanup** |
| `PAGE_SIZE` | No | `100` | Issues per API page (max 100) |
| `MAX_RETRIES` | No | `3` | Max attempts per request, including the first; set it to 1 or more |
| `READ_TIMEOUT` | No | `30` | HTTP read timeout in seconds for API calls; `0` = no timeout. Attachment downloads use a fixed 600 s read timeout, uploads none |
| `API_DELAY` | No | `0.2` | Seconds to wait between API calls |
| `CHUNK_SIZE` | No | `8192` | Bytes per chunk when streaming attachment downloads |
| `INCLUDE_ATTACHMENTS` | No | `true` | Download attachment binary files |
| `INCLUDE_CHANGELOG` | No | `true` | Include field change history in issues |
| `INCLUDE_WORKLOGS` | No | `true` | Include time tracking entries |
| `LEGACY_KEY_JQL_TEMPLATE` | No | — | Fallback JQL for **Upload attachments only** (menu option 5), used when `key_mapping.json` has no entry for an issue. Placeholders: `{orig_key}`, `{project_key}` — e.g. `project = {project_key} AND "Original Key" = "{orig_key}"` |

> \* Either `JIRA_EMAIL` + `JIRA_API_TOKEN` **or** `JIRA_COOKIE_HEADER` is required.

---

## Requirements

- Python **3.10+**
- [`requests`](https://pypi.org/project/requests/) >= 2.28
- [`python-dotenv`](https://pypi.org/project/python-dotenv/) >= 1.0

---

## Changelog

See [CHANGELOG.md](https://github.com/davidmalko87/jira-project-backup-restore/blob/master/CHANGELOG.md) for the full version history.

## Contributing

See [CONTRIBUTING.md](https://github.com/davidmalko87/jira-project-backup-restore/blob/master/CONTRIBUTING.md) for the development setup, the versioning policy, and the release steps.

## License

[MIT](https://github.com/davidmalko87/jira-project-backup-restore/blob/master/LICENSE)
