1use std::io::Write;
2
3use anyhow::Result;
4use clap::Subcommand;
5use colored::Colorize;
6use tabled::{Table, Tabled};
7
8use super::commit::{author_label, first_line_truncated, short_hash};
9use super::{output_json, parse_repo, print_json};
10use crate::api::BitbucketClient;
11use crate::cli::pagination::{effective_limit, format_size};
12
13const MSG_WIDTH: usize = 50;
15
16#[derive(Subcommand)]
17pub enum FileCommands {
18 Ls {
20 repo: String,
22
23 #[arg(default_value = "")]
25 path: String,
26
27 #[arg(short = 'r', long = "ref", value_name = "REF")]
29 git_ref: Option<String>,
30
31 #[arg(short, long, default_value = "25")]
33 limit: u32,
34 },
35
36 Cat {
38 repo: String,
40
41 path: String,
43
44 #[arg(short = 'r', long = "ref", value_name = "REF")]
46 git_ref: Option<String>,
47 },
48
49 History {
51 repo: String,
53
54 path: String,
56
57 #[arg(short = 'r', long = "ref", value_name = "REF")]
59 git_ref: Option<String>,
60
61 #[arg(short, long, default_value = "25")]
63 limit: u32,
64 },
65}
66
67#[derive(Tabled)]
68struct SourceRow {
69 #[tabled(rename = "TYPE")]
70 entry_type: String,
71 #[tabled(rename = "SIZE")]
72 size: String,
73 #[tabled(rename = "PATH")]
74 path: String,
75}
76
77#[derive(Tabled)]
78struct HistoryRow {
79 #[tabled(rename = "COMMIT")]
80 commit: String,
81 #[tabled(rename = "AUTHOR")]
82 author: String,
83 #[tabled(rename = "DATE")]
84 date: String,
85 #[tabled(rename = "MESSAGE")]
86 message: String,
87}
88
89impl FileCommands {
90 pub async fn run(self) -> Result<()> {
91 match self {
92 FileCommands::Ls {
93 repo,
94 path,
95 git_ref,
96 limit,
97 } => {
98 let (workspace, repo_slug) = parse_repo(&repo)?;
99 let client = BitbucketClient::from_stored().await?;
100 let git_ref = resolve_ref(&client, &workspace, &repo_slug, git_ref).await?;
101
102 let entries = client
103 .list_source(
104 &workspace,
105 &repo_slug,
106 &git_ref,
107 &path,
108 None,
109 Some(effective_limit(limit)),
110 )
111 .await?;
112
113 if output_json() {
114 return print_json(&entries.values);
115 }
116
117 if entries.values.is_empty() {
118 println!("No entries found at '{}' in {} ({})", path, repo, git_ref);
119 return Ok(());
120 }
121
122 let rows: Vec<SourceRow> = entries
123 .values
124 .iter()
125 .map(|e| SourceRow {
126 entry_type: entry_type_label(&e.entry_type).to_string(),
127 size: e.size.map(format_size).unwrap_or_else(|| "-".to_string()),
128 path: e.path.clone(),
129 })
130 .collect();
131
132 println!("{}", Table::new(rows));
133
134 if entries.next.is_some() {
135 println!(
136 "\n{} More entries available. Use --limit to see more.",
137 "ℹ".blue()
138 );
139 }
140
141 Ok(())
142 }
143
144 FileCommands::Cat {
145 repo,
146 path,
147 git_ref,
148 } => {
149 let (workspace, repo_slug) = parse_repo(&repo)?;
150 let client = BitbucketClient::from_stored().await?;
151 let git_ref = resolve_ref(&client, &workspace, &repo_slug, git_ref).await?;
152
153 let content = client
154 .get_file_raw(&workspace, &repo_slug, &git_ref, &path)
155 .await?;
156
157 print!("{}", content);
160 std::io::stdout().flush()?;
161
162 Ok(())
163 }
164
165 FileCommands::History {
166 repo,
167 path,
168 git_ref,
169 limit,
170 } => {
171 let (workspace, repo_slug) = parse_repo(&repo)?;
172 let client = BitbucketClient::from_stored().await?;
173 let git_ref = resolve_ref(&client, &workspace, &repo_slug, git_ref).await?;
174
175 let history = client
176 .get_file_history(
177 &workspace,
178 &repo_slug,
179 &git_ref,
180 &path,
181 Some(effective_limit(limit)),
182 )
183 .await?;
184
185 if output_json() {
186 return print_json(&history.values);
187 }
188
189 if history.values.is_empty() {
190 println!("No history found for '{}' in {} ({})", path, repo, git_ref);
191 return Ok(());
192 }
193
194 let rows: Vec<HistoryRow> = history
195 .values
196 .iter()
197 .map(|entry| {
198 let commit = entry.commit.as_ref();
199 HistoryRow {
200 commit: commit.map(|c| short_hash(&c.hash)).unwrap_or_default(),
201 author: commit
202 .map(|c| author_label(c.author.as_ref()))
203 .unwrap_or_else(|| "-".to_string()),
204 date: commit
205 .and_then(|c| c.date)
206 .map(|d| d.format("%Y-%m-%d").to_string())
207 .unwrap_or_default(),
208 message: commit
209 .and_then(|c| c.message.as_deref())
210 .map(|m| first_line_truncated(m, MSG_WIDTH))
211 .unwrap_or_default(),
212 }
213 })
214 .collect();
215
216 println!("{}", Table::new(rows));
217
218 if history.next.is_some() {
219 println!(
220 "\n{} More history available. Use --limit to see more.",
221 "ℹ".blue()
222 );
223 }
224
225 Ok(())
226 }
227 }
228 }
229}
230
231async fn resolve_ref(
234 client: &BitbucketClient,
235 workspace: &str,
236 repo_slug: &str,
237 git_ref: Option<String>,
238) -> Result<String> {
239 if let Some(r) = git_ref {
240 return Ok(r);
241 }
242
243 let repository = client.get_repository(workspace, repo_slug).await?;
244 Ok(repository
245 .mainbranch
246 .map(|b| b.name)
247 .unwrap_or_else(|| "main".to_string()))
248}
249
250fn entry_type_label(entry_type: &str) -> &str {
252 match entry_type {
253 "commit_file" => "file",
254 "commit_directory" => "dir",
255 other => other,
256 }
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262
263 #[test]
264 fn entry_type_label_maps_known_types() {
265 assert_eq!(entry_type_label("commit_file"), "file");
266 assert_eq!(entry_type_label("commit_directory"), "dir");
267 }
268
269 #[test]
270 fn entry_type_label_passes_through_unknown_types() {
271 assert_eq!(entry_type_label("commit_submodule"), "commit_submodule");
272 }
273}