torrust-tracker-deployer 0.1.0

Torrust Tracker Deployer - Deployment Infrastructure with Ansible and OpenTofu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# Linting Conventions and Tools

This document covers the linting tools, configurations, and conventions used in the Torrust Tracker Deployer project.

## 🔧 Linting Tools Overview

We use multiple linting tools to maintain code quality across different file types:

| Tool               | Purpose                       | File Types        | Configuration               |
| ------------------ | ----------------------------- | ----------------- | --------------------------- |
| `markdownlint-cli` | Markdown formatting and style | `*.md`            | `.markdownlint.json`        |
| `yamllint`         | YAML syntax and style         | `*.yml`, `*.yaml` | `.yamllint-ci.yml`          |
| `taplo`            | TOML formatting and linting   | `*.toml`          | `.taplo.toml`               |
| `cspell`           | Spell checking                | All text files    | `cspell.json`               |
| `shellcheck`       | Shell script analysis         | `*.sh`, `*.bash`  | Built-in rules              |
| `clippy`           | Rust code analysis            | `*.rs`            | `Cargo.toml` + command args |
| `rustfmt`          | Rust code formatting          | `*.rs`            | `rustfmt.toml` (default)    |

## 🚀 Quick Start

**Run all linters** (recommended):

```bash
cargo run --bin linter all
```

**Run individual linters**:

```bash
# Individual linters
cargo run --bin linter markdown
```

**YAML linting**:

```bash
cargo run --bin linter yaml
```

**TOML linting**:

```bash
cargo run --bin linter toml
```

**Spell checking**:

```bash
cargo run --bin linter cspell
```

**Rust code analysis**:

```bash
cargo run --bin linter clippy
```

**Rust formatting**:

```bash
cargo run --bin linter rustfmt
```

**Shell script linting**:

```bash
cargo run --bin linter shellcheck
```

### Linting Implementation

All linting is managed through a unified Rust binary (`src/bin/linter.rs`) that wraps the individual linting tools. This provides:

- **Consistent interface**: Single command structure across all linters
- **Better error handling**: Structured error messages and exit codes
- **Unified logging**: Consistent output formatting
- **Easy extensibility**: Add new linters by implementing the `Linter` trait

The linter binary uses the [`torrust-linting`](https://crates.io/crates/torrust-linting) crate, which provides a reusable linting framework published to crates.io.

### Alternative: Shell Script Wrapper

A convenience wrapper script is available:

```bash
# Wrapper that calls the Rust binary
./scripts/lint.sh
```

This script simply invokes `cargo run --bin linter all` and is provided for backwards compatibility.

## 📋 Tool-Specific Guidelines

### Markdown Linting (`markdownlint-cli`)

**Configuration**: `.markdownlint.json`

Key rules enabled:

- ✅ **MD031**: Fenced code blocks surrounded by blank lines
- ✅ **MD032**: Lists surrounded by blank lines
- ✅ **MD040**: Fenced code blocks have language specified
- ✅ **MD022**: Headings surrounded by blank lines
- ✅ **MD009**: No trailing spaces
- ❌ **MD013**: Line length (disabled for flexibility)
- ❌ **MD041**: First line in file should be top-level heading (disabled)
- ❌ **MD060**: Table column style (disabled - allows flexible table formatting and emoji usage)

**Common fixes**:

```bash
# Add language to code blocks
# Bad:
```

```text
code here
```

```bash
# Good:
```

```bash
code here
```

```text
# Add blank lines around headings and lists
```

### YAML Linting (`yamllint`)

**Configuration**: `.yamllint-ci.yml`

Key settings:

- **Line length**: 200 characters (extended for infrastructure code)
- **Comments**: Minimum 1 space from content
- **Document start**: Disabled (for cloud-init compatibility)
- **Truthy values**: Allows common values (`true`, `false`, `yes`, `no`, `on`, `off`)

**Common fixes**:

```yaml
# Ensure proper indentation (2 spaces)
services:
  web:
    image: nginx
    ports:
      - "80:80"

# Use consistent quotes
name: "my-service"
version: "1.0" # Consistent with project style
```

### TOML Linting (`taplo`)

**Configuration**: `.taplo.toml`

Key settings:

- **Formatting**: Preserves blank lines and doesn't reorder keys
- **Arrays**: Trailing commas enabled, consistent expansion
- **Alignment**: Comments aligned, entries not aligned for readability
- **Indentation**: Tables and entries maintain natural structure

**Common fixes**:

```toml
# Use consistent formatting
[dependencies]
serde = { version = "1.0", features = ["derive"] }
tokio = "1.0"

# Arrays with trailing commas
features = [
    "derive",
    "serde",
]

# Proper spacing around values
name = "torrust-tracker"  # Good
name="torrust-tracker"    # Bad - needs spaces
```

**Auto-fix formatting**:

```bash
# Fix all TOML files automatically
taplo fmt **/*.toml
```

### Spell Checking (`cspell`)

**Configuration**: `cspell.json`

Key settings:

- **Custom dictionary**: `project-words.txt` for project-specific terms
- **Language**: English (US)
- **File types**: All text files (markdown, code, configs)

**Common workflow**:

```bash
# Add new words to project dictionary
echo "torrust" >> project-words.txt
echo "opentofu" >> project-words.txt

# Run spell check
cargo run --bin linter cspell
```

### Excluded Directories

**Important**: The following directories contain **generated or runtime data** and are excluded from all linting:

- `build/` - Generated build artifacts and rendered templates
- `data/` - Runtime application data and test outputs
- `envs/` - User environment configurations (JSON files)

These directories are configured to be ignored in:

- `.taplo.toml` - TOML linting exclusions
- `.markdownlint.json` - Markdown linting exclusions (via `ignores`)
- `.yamllint-ci.yml` - YAML linting exclusions (via `ignore`)
- `cspell.json` - Spell check exclusions (via `ignorePaths`)

**Why exclude these folders?**

1. **Generated content**: Linting generated files creates noise and false positives
2. **User data**: Environment configs are user-specific and may not follow project conventions
3. **Test artifacts**: Temporary test data shouldn't affect linting status
4. **Performance**: Excluding these folders significantly speeds up linting

If you add a new linting tool, ensure these directories are excluded from its scope.

### Shell Script Linting (`shellcheck`)

**Configuration**: Built-in ShellCheck rules

**Common fixes**:

```bash
# Quote variables to prevent word splitting
echo "$variable" # Good
echo $variable   # Bad

# Use [[ ]] instead of [ ] for conditionals
if [[ "$var" == "value" ]]; then # Good
if [ "$var" == "value" ]; then   # OK but prefer [[]]

# Check command existence
if command -v docker &> /dev/null; then # Good
if which docker; then                   # Less portable
```

### Rust Code Analysis (`clippy`)

**Configuration**: Command-line arguments in `scripts/linting/clippy.sh`

Enabled lint groups:

- **Correctness**: `-D clippy::correctness`
- **Suspicious**: `-D clippy::suspicious`
- **Complexity**: `-D clippy::complexity`
- **Performance**: `-D clippy::perf`
- **Style**: `-D clippy::style`
- **Pedantic**: `-D clippy::pedantic`

**Common fixes**:

```rust
// Use ? operator instead of unwrap
let value = some_function()?; // Good
let value = some_function().unwrap(); // Avoid in production code

// Prefer matches! macro for simple boolean checks
if matches!(status, Status::Ready) // Good
if status == Status::Ready // Also fine, but matches! is more explicit

// Use clippy suggestions for better performance
let items: Vec<_> = iterator.collect(); // Often suggested improvements
```

### Rust Formatting (`rustfmt`)

**Configuration**: Default `rustfmt` settings

**Automatic formatting**:

```bash
# Format code (modifies files)
cargo fmt

# Check formatting without modifying
cargo fmt -- --check
```

## 📁 Configuration Files

### `.markdownlint.json`

```json
{
  "default": true,
  "MD013": false, // Line length disabled
  "MD031": true, // Fenced code blocks surrounded by blank lines
  "MD032": true, // Lists surrounded by blank lines
  "MD040": true, // Fenced code blocks have language
  "MD022": true, // Headings surrounded by blank lines
  "MD009": true, // No trailing spaces
  "MD007": {
    // Unordered list indentation
    "indent": 2
  },
  "MD026": false, // Trailing punctuation in headings
  "MD041": false, // First line in file should be top-level heading
  "MD034": false, // Bare URL used
  "MD024": false, // Multiple headings with same content
  "MD033": false // Inline HTML
}
```

### `.yamllint-ci.yml`

```yaml
extends: default

rules:
  line-length:
    max: 200 # More reasonable for infrastructure code
  comments:
    min-spaces-from-content: 1 # Allow single space before comments
  document-start: disable # Cloud-init files don't need --- start
  truthy:
    allowed-values: ["true", "false", "yes", "no", "on", "off"]

# Ignore cloud-init files for comment spacing
ignore: |
  **/cloud-init.yml
```

## 🔄 CI/CD Integration

### GitHub Actions Workflow

The same linting binary runs in CI/CD (`.github/workflows/linting.yml`):

```yaml
- name: Build Rust linter
  run: cargo build --release --bin linter

- name: Run all linters
  run: ./target/release/linter all
```

This ensures **consistency between local development and CI environments**.

### Pre-commit Integration

Integrate linting into your Git workflow:

```bash
#!/bin/bash
# .git/hooks/pre-commit
if ! cargo run --bin linter all; then
    echo "❌ Linting failed. Please fix issues before committing."
    exit 1
fi
```

## 📦 Tool Installation

The linting scripts automatically install required tools if missing:

### Automatic Installation

- **markdownlint-cli**: Installed via `npm install -g markdownlint-cli`
- **yamllint**: Installed via system package manager (`apt`, `dnf`, `pacman`) or `pip3`
- **shellcheck**: Installed via system package manager
- **clippy & rustfmt**: Installed as part of Rust toolchain

### Manual Installation

```bash
# Node.js tools
npm install -g markdownlint-cli

# Python tools
pip3 install yamllint

# System tools (Ubuntu/Debian)
sudo apt install shellcheck

# Rust tools
rustup component add clippy rustfmt
```

## 🎯 Best Practices

### Before Committing

1. **Always run linters**: `cargo run --bin linter all`
2. **Fix all issues**: Don't commit with linting errors
3. **Understand the rules**: Learn why rules exist, don't just fix blindly

### Code Organization

1. **Keep configs in root**: All linting configs should be in project root
2. **Document exceptions**: If you disable a rule, explain why
3. **Consistent style**: Follow existing patterns in the codebase

### Performance Tips

```bash
# Run specific linters for faster feedback during development
cargo run --bin linter markdown    # Only markdown (~1s)
cargo run --bin linter yaml        # Only YAML files (~0.2s)
cargo run --bin linter toml        # Only TOML files (~0.1s)
cargo run --bin linter cspell      # Spell check (~2.5s)
cargo run --bin linter clippy      # Only Rust analysis (~12s - slowest)

# Run non-Rust linters for quick checks
cargo run --bin linter markdown
cargo run --bin linter yaml
cargo run --bin linter toml
cargo run --bin linter cspell
# Skip clippy for faster iteration during active development
```

**Tip**: The linter binary runs tools sequentially with clean output. For fastest iteration during development, run only the linter relevant to the files you're editing.

## 🚨 Troubleshooting

### Common Issues

**Linter not found**:

```bash
# The scripts auto-install tools, but if it fails:
npm install -g markdownlint-cli  # For markdown
pip3 install yamllint           # For YAML
```

**Permission errors**:

```bash
# Make scripts executable
chmod +x scripts/linting/*.sh
```

**Rust toolchain issues**:

```bash
# Ensure clippy and rustfmt are installed
rustup component add clippy rustfmt
```

### Getting Help

1. **Check existing issues**: Look for similar problems in GitHub issues
2. **Run with verbose output**: Add `-v` or `--verbose` flags where available
3. **Manual tool execution**: Try running tools directly to isolate issues

## 📊 Linting Statistics

Track your linting improvements:

```bash
# Count linting issues over time
git log --grep="fix.*lint\|style:" --oneline | wc -l

# Check files that frequently need linting fixes
git log --name-only --grep="style\|lint" | sort | uniq -c | sort -nr
```