guts-compat 0.1.0

Git and GitHub compatibility layer for Guts code collaboration platform.
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
//! Release and tag management types.

use serde::{Deserialize, Serialize};
use std::time::{SystemTime, UNIX_EPOCH};

/// Unique identifier for a release.
pub type ReleaseId = u64;

/// Unique identifier for a release asset.
pub type AssetId = u64;

/// A release (tagged version) in a repository.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Release {
    /// Unique release ID.
    pub id: ReleaseId,
    /// Repository key (owner/name).
    pub repo_key: String,
    /// Tag name (e.g., "v1.0.0").
    pub tag_name: String,
    /// Target branch or commit SHA.
    pub target_commitish: String,
    /// Release title (optional).
    pub name: Option<String>,
    /// Markdown body (changelog, notes).
    pub body: Option<String>,
    /// Whether this is a draft release.
    pub draft: bool,
    /// Whether this is a prerelease.
    pub prerelease: bool,
    /// Username of the author.
    pub author: String,
    /// Attached assets.
    pub assets: Vec<ReleaseAsset>,
    /// When the release was created.
    pub created_at: u64,
    /// When the release was published (None if draft).
    pub published_at: Option<u64>,
}

impl Release {
    /// Create a new release.
    pub fn new(
        id: ReleaseId,
        repo_key: String,
        tag_name: String,
        target_commitish: String,
        author: String,
    ) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();

        Self {
            id,
            repo_key,
            tag_name,
            target_commitish,
            name: None,
            body: None,
            draft: false,
            prerelease: false,
            author,
            assets: Vec::new(),
            created_at: now,
            published_at: Some(now),
        }
    }

    /// Check if this is the latest non-prerelease, non-draft release.
    pub fn is_publishable(&self) -> bool {
        !self.draft && !self.prerelease
    }

    /// Publish a draft release.
    pub fn publish(&mut self) {
        self.draft = false;
        self.published_at = Some(
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
        );
    }

    /// Add an asset to this release.
    pub fn add_asset(&mut self, asset: ReleaseAsset) {
        self.assets.push(asset);
    }

    /// Remove an asset by ID.
    pub fn remove_asset(&mut self, asset_id: AssetId) -> Option<ReleaseAsset> {
        if let Some(pos) = self.assets.iter().position(|a| a.id == asset_id) {
            Some(self.assets.remove(pos))
        } else {
            None
        }
    }

    /// Convert to API response.
    pub fn to_response(&self) -> ReleaseResponse {
        ReleaseResponse {
            id: self.id,
            tag_name: self.tag_name.clone(),
            target_commitish: self.target_commitish.clone(),
            name: self.name.clone(),
            body: self.body.clone(),
            draft: self.draft,
            prerelease: self.prerelease,
            author: AuthorInfo {
                login: self.author.clone(),
            },
            assets: self.assets.iter().map(|a| a.to_response()).collect(),
            created_at: format_timestamp(self.created_at),
            published_at: self.published_at.map(format_timestamp),
        }
    }
}

/// An asset attached to a release.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseAsset {
    /// Unique asset ID.
    pub id: AssetId,
    /// Release this asset belongs to.
    pub release_id: ReleaseId,
    /// Filename.
    pub name: String,
    /// Optional label for display.
    pub label: Option<String>,
    /// MIME content type.
    pub content_type: String,
    /// Size in bytes.
    pub size: u64,
    /// Download count.
    pub download_count: u64,
    /// SHA-256 hash of content.
    pub content_hash: String,
    /// When the asset was uploaded.
    pub created_at: u64,
    /// Username of uploader.
    pub uploader: String,
}

impl ReleaseAsset {
    /// Create a new asset.
    pub fn new(
        id: AssetId,
        release_id: ReleaseId,
        name: String,
        content_type: String,
        size: u64,
        content_hash: String,
        uploader: String,
    ) -> Self {
        Self {
            id,
            release_id,
            name,
            label: None,
            content_type,
            size,
            download_count: 0,
            content_hash,
            created_at: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_secs(),
            uploader,
        }
    }

    /// Increment the download count.
    pub fn increment_downloads(&mut self) {
        self.download_count += 1;
    }

    /// Convert to API response.
    pub fn to_response(&self) -> AssetResponse {
        AssetResponse {
            id: self.id,
            name: self.name.clone(),
            label: self.label.clone(),
            content_type: self.content_type.clone(),
            size: self.size,
            download_count: self.download_count,
            created_at: format_timestamp(self.created_at),
            uploader: AuthorInfo {
                login: self.uploader.clone(),
            },
        }
    }
}

/// Author information for responses.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthorInfo {
    /// Username.
    pub login: String,
}

/// Release response for API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReleaseResponse {
    /// Release ID.
    pub id: ReleaseId,
    /// Tag name.
    pub tag_name: String,
    /// Target branch/commit.
    pub target_commitish: String,
    /// Release title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    /// Markdown body.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub body: Option<String>,
    /// Whether this is a draft.
    pub draft: bool,
    /// Whether this is a prerelease.
    pub prerelease: bool,
    /// Author information.
    pub author: AuthorInfo,
    /// Attached assets.
    pub assets: Vec<AssetResponse>,
    /// Creation timestamp.
    pub created_at: String,
    /// Publication timestamp.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub published_at: Option<String>,
}

/// Asset response for API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AssetResponse {
    /// Asset ID.
    pub id: AssetId,
    /// Filename.
    pub name: String,
    /// Optional label.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    /// MIME content type.
    pub content_type: String,
    /// Size in bytes.
    pub size: u64,
    /// Download count.
    pub download_count: u64,
    /// Upload timestamp.
    pub created_at: String,
    /// Uploader information.
    pub uploader: AuthorInfo,
}

/// Request to create a release.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CreateReleaseRequest {
    /// Tag name (required).
    pub tag_name: String,
    /// Target branch or commit (default: default branch).
    #[serde(default)]
    pub target_commitish: Option<String>,
    /// Release title.
    #[serde(default)]
    pub name: Option<String>,
    /// Markdown body.
    #[serde(default)]
    pub body: Option<String>,
    /// Create as draft.
    #[serde(default)]
    pub draft: bool,
    /// Mark as prerelease.
    #[serde(default)]
    pub prerelease: bool,
}

/// Request to update a release.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UpdateReleaseRequest {
    /// New tag name.
    #[serde(default)]
    pub tag_name: Option<String>,
    /// New target.
    #[serde(default)]
    pub target_commitish: Option<String>,
    /// New title.
    #[serde(default)]
    pub name: Option<String>,
    /// New body.
    #[serde(default)]
    pub body: Option<String>,
    /// Update draft status.
    #[serde(default)]
    pub draft: Option<bool>,
    /// Update prerelease status.
    #[serde(default)]
    pub prerelease: Option<bool>,
}

/// Format a Unix timestamp as ISO 8601.
fn format_timestamp(timestamp: u64) -> String {
    let secs_per_day = 86400;
    let secs_per_hour = 3600;
    let secs_per_min = 60;

    let mut days = timestamp / secs_per_day;
    let remaining = timestamp % secs_per_day;
    let hours = remaining / secs_per_hour;
    let remaining = remaining % secs_per_hour;
    let minutes = remaining / secs_per_min;
    let seconds = remaining % secs_per_min;

    let mut year = 1970;
    loop {
        let days_in_year = if is_leap_year(year) { 366 } else { 365 };
        if days < days_in_year {
            break;
        }
        days -= days_in_year;
        year += 1;
    }

    let days_in_month = if is_leap_year(year) {
        [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
        [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    };

    let mut month = 0;
    for (i, &dim) in days_in_month.iter().enumerate() {
        if days < dim as u64 {
            month = i + 1;
            break;
        }
        days -= dim as u64;
    }
    let day = days + 1;

    format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z",
        year, month, day, hours, minutes, seconds
    )
}

fn is_leap_year(year: u64) -> bool {
    (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_release_creation() {
        let release = Release::new(
            1,
            "alice/repo".to_string(),
            "v1.0.0".to_string(),
            "main".to_string(),
            "alice".to_string(),
        );

        assert_eq!(release.id, 1);
        assert_eq!(release.tag_name, "v1.0.0");
        assert!(!release.draft);
        assert!(!release.prerelease);
        assert!(release.published_at.is_some());
    }

    #[test]
    fn test_draft_release() {
        let mut release = Release::new(
            1,
            "alice/repo".to_string(),
            "v1.0.0".to_string(),
            "main".to_string(),
            "alice".to_string(),
        );

        release.draft = true;
        release.published_at = None;

        assert!(!release.is_publishable());

        release.publish();
        assert!(release.is_publishable());
        assert!(release.published_at.is_some());
    }

    #[test]
    fn test_asset_management() {
        let mut release = Release::new(
            1,
            "alice/repo".to_string(),
            "v1.0.0".to_string(),
            "main".to_string(),
            "alice".to_string(),
        );

        let asset = ReleaseAsset::new(
            1,
            1,
            "app-v1.0.0.tar.gz".to_string(),
            "application/gzip".to_string(),
            1024,
            "abc123".to_string(),
            "alice".to_string(),
        );

        release.add_asset(asset);
        assert_eq!(release.assets.len(), 1);

        let removed = release.remove_asset(1);
        assert!(removed.is_some());
        assert_eq!(release.assets.len(), 0);
    }

    #[test]
    fn test_asset_downloads() {
        let mut asset = ReleaseAsset::new(
            1,
            1,
            "app.tar.gz".to_string(),
            "application/gzip".to_string(),
            1024,
            "abc123".to_string(),
            "alice".to_string(),
        );

        assert_eq!(asset.download_count, 0);
        asset.increment_downloads();
        asset.increment_downloads();
        assert_eq!(asset.download_count, 2);
    }
}