itcpr 2.0.7__tar.gz → 2.0.8__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
itcpr-2.0.8/LICENSE ADDED
File without changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: itcpr
3
- Version: 2.0.7
3
+ Version: 2.0.8
4
4
  Summary: CLI tool for syncing GitHub repositories from ITCPR Cloud
5
5
  Home-page: https://itcpr.org
6
6
  Author: ITCPR
@@ -38,7 +38,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
38
38
 
39
39
  ## Features
40
40
 
41
- - 🔐 Device-based authentication with cloud.itcpr.org
41
+ - 🔐 Device-based authentication with ITCPR Cloud
42
42
  - 📦 Automatic repository synchronization
43
43
  - 🔄 Manual or continuous sync modes
44
44
  - 💾 Local SQLite database for metadata tracking
@@ -107,7 +107,7 @@ rm -rf ~/.itcpr
107
107
 
108
108
  - Python 3.10+
109
109
  - Git (system installation)
110
- - Access to cloud.itcpr.org
110
+ - Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
111
111
 
112
112
  ## Quick Start
113
113
 
@@ -187,7 +187,7 @@ itcpr logout
187
187
 
188
188
  ### `itcpr login`
189
189
 
190
- Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls for approval.
190
+ Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls the API at `api.itcpr.org` for approval.
191
191
 
192
192
  ### `itcpr logout`
193
193
 
@@ -304,11 +304,37 @@ pip install itcpr[yaml]
304
304
  pip install PyYAML
305
305
  ```
306
306
 
307
+ ## Development / Mock Mode
308
+
309
+ When the API at `api.itcpr.org` is unavailable, the CLI automatically falls back to mock API responses for testing and development.
310
+
311
+ **Automatic Mock Mode:**
312
+ - If the backend returns 404 or is unreachable, mock responses are used automatically
313
+ - You'll see a warning: "⚠️ Backend unavailable, using mock mode for testing"
314
+
315
+ **Manual Mock Mode:**
316
+ You can also enable mock mode explicitly:
317
+
318
+ ```bash
319
+ # Using environment variable
320
+ export ITCPR_MOCK_MODE=true
321
+ itcpr login
322
+
323
+ # Or set in config file (~/.itcpr/config.toml)
324
+ # mock_mode = true
325
+ ```
326
+
327
+ **Mock Features:**
328
+ - Auto-approves device login after 2 seconds
329
+ - Provides sample user and repository data
330
+ - Generates mock GitHub tokens
331
+ - All commands work in mock mode for testing
332
+
307
333
  ## Troubleshooting
308
334
 
309
335
  ### "Not logged in" error
310
336
 
311
- Run `itcpr login` to authenticate your device.
337
+ Run `itcpr login` to authenticate your device. If the backend is unavailable, mock mode will activate automatically.
312
338
 
313
339
  ### "Repository not assigned" error
314
340
 
@@ -4,7 +4,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
4
4
 
5
5
  ## Features
6
6
 
7
- - 🔐 Device-based authentication with cloud.itcpr.org
7
+ - 🔐 Device-based authentication with ITCPR Cloud
8
8
  - 📦 Automatic repository synchronization
9
9
  - 🔄 Manual or continuous sync modes
10
10
  - 💾 Local SQLite database for metadata tracking
@@ -73,7 +73,7 @@ rm -rf ~/.itcpr
73
73
 
74
74
  - Python 3.10+
75
75
  - Git (system installation)
76
- - Access to cloud.itcpr.org
76
+ - Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
77
77
 
78
78
  ## Quick Start
79
79
 
@@ -153,7 +153,7 @@ itcpr logout
153
153
 
154
154
  ### `itcpr login`
155
155
 
156
- Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls for approval.
156
+ Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls the API at `api.itcpr.org` for approval.
157
157
 
158
158
  ### `itcpr logout`
159
159
 
@@ -270,11 +270,37 @@ pip install itcpr[yaml]
270
270
  pip install PyYAML
271
271
  ```
272
272
 
273
+ ## Development / Mock Mode
274
+
275
+ When the API at `api.itcpr.org` is unavailable, the CLI automatically falls back to mock API responses for testing and development.
276
+
277
+ **Automatic Mock Mode:**
278
+ - If the backend returns 404 or is unreachable, mock responses are used automatically
279
+ - You'll see a warning: "⚠️ Backend unavailable, using mock mode for testing"
280
+
281
+ **Manual Mock Mode:**
282
+ You can also enable mock mode explicitly:
283
+
284
+ ```bash
285
+ # Using environment variable
286
+ export ITCPR_MOCK_MODE=true
287
+ itcpr login
288
+
289
+ # Or set in config file (~/.itcpr/config.toml)
290
+ # mock_mode = true
291
+ ```
292
+
293
+ **Mock Features:**
294
+ - Auto-approves device login after 2 seconds
295
+ - Provides sample user and repository data
296
+ - Generates mock GitHub tokens
297
+ - All commands work in mock mode for testing
298
+
273
299
  ## Troubleshooting
274
300
 
275
301
  ### "Not logged in" error
276
302
 
277
- Run `itcpr login` to authenticate your device.
303
+ Run `itcpr login` to authenticate your device. If the backend is unavailable, mock mode will activate automatically.
278
304
 
279
305
  ### "Repository not assigned" error
280
306
 
@@ -1,4 +1,4 @@
1
1
  """ITCPR Agent - CLI tool for syncing GitHub repositories."""
2
2
 
3
- __version__ = "2.0.7"
3
+ __version__ = "2.0.8"
4
4
 
@@ -0,0 +1,115 @@
1
+ """API client for api.itcpr.org."""
2
+
3
+ import requests
4
+ from typing import List, Dict, Any, Optional
5
+ from .auth import Auth
6
+ from .config import config
7
+ from .utils import get_logger, print_error
8
+
9
+ logger = get_logger(__name__)
10
+
11
+ # Import mock API for fallback
12
+ try:
13
+ from .mock_api import _mock_api
14
+ MOCK_AVAILABLE = True
15
+ except ImportError:
16
+ MOCK_AVAILABLE = False
17
+ _mock_api = None
18
+
19
+ class APIClient:
20
+ """Client for ITCPR Cloud API."""
21
+
22
+ def __init__(self, auth: Auth):
23
+ self.auth = auth
24
+ self.api_base = auth.api_base
25
+
26
+ def _get_headers(self) -> Dict[str, str]:
27
+ """Get request headers with authentication."""
28
+ headers = {"Content-Type": "application/json"}
29
+ token = self.auth.get_token()
30
+ if token:
31
+ headers["Authorization"] = f"Bearer {token}"
32
+ return headers
33
+
34
+ def _request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
35
+ """Make authenticated API request."""
36
+ url = f"{self.api_base}{endpoint}"
37
+ headers = self._get_headers()
38
+ headers.update(kwargs.pop("headers", {}))
39
+
40
+ use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
41
+
42
+ try:
43
+ response = requests.request(method, url, headers=headers, timeout=5 if use_mock else 30, **kwargs)
44
+ # If we get 404 and mock is available, we'll handle it in the calling methods
45
+ return response
46
+ except requests.RequestException as e:
47
+ if use_mock:
48
+ logger.debug(f"API request failed, will use mock: {e}")
49
+ else:
50
+ logger.error(f"API request failed: {e}")
51
+ raise
52
+
53
+ def get_me(self) -> Dict[str, Any]:
54
+ """Get current user/device information."""
55
+ use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
56
+
57
+ try:
58
+ response = self._request("GET", "/api/agent/me")
59
+ response.raise_for_status()
60
+ return response.json()
61
+ except (requests.HTTPError, requests.RequestException) as e:
62
+ if use_mock and (isinstance(e, requests.HTTPError) and e.response.status_code == 404):
63
+ logger.info("Backend unavailable, using mock API")
64
+ return _mock_api.get_me()
65
+ raise
66
+
67
+ def get_repos(self) -> List[Dict[str, Any]]:
68
+ """Get list of assigned repositories."""
69
+ use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
70
+
71
+ try:
72
+ response = self._request("GET", "/api/agent/repos")
73
+ response.raise_for_status()
74
+ data = response.json()
75
+ return data.get("repos", [])
76
+ except (requests.HTTPError, requests.RequestException) as e:
77
+ if use_mock and (isinstance(e, requests.HTTPError) and e.response.status_code == 404):
78
+ logger.info("Backend unavailable, using mock API")
79
+ return _mock_api.get_repos()
80
+ raise
81
+
82
+ def get_github_token(self, repo_name: Optional[str] = None) -> str:
83
+ """Get short-lived GitHub installation token."""
84
+ use_mock = config.mock_mode or (MOCK_AVAILABLE and _mock_api is not None)
85
+
86
+ payload = {}
87
+ if repo_name:
88
+ payload["repo"] = repo_name
89
+
90
+ try:
91
+ response = self._request("POST", "/api/agent/token", json=payload)
92
+ response.raise_for_status()
93
+ data = response.json()
94
+ token = data.get("token")
95
+ if not token:
96
+ raise ValueError("Token not found in response")
97
+ return token
98
+ except (requests.HTTPError, requests.RequestException) as e:
99
+ if use_mock and (isinstance(e, requests.HTTPError) and e.response.status_code == 404):
100
+ logger.info("Backend unavailable, using mock API")
101
+ return _mock_api.get_github_token(repo_name)
102
+ raise
103
+
104
+ def validate_token(self) -> bool:
105
+ """Validate current device token."""
106
+ try:
107
+ self.get_me()
108
+ return True
109
+ except requests.HTTPError as e:
110
+ if e.response.status_code == 401:
111
+ return False
112
+ raise
113
+ except Exception:
114
+ return False
115
+
@@ -0,0 +1,296 @@
1
+ """Authentication management for ITCPR Agent."""
2
+
3
+ import keyring
4
+ import time
5
+ import webbrowser
6
+ import requests
7
+ import socket
8
+ import platform
9
+ from typing import Optional, Dict, Any
10
+ from .config import config
11
+ from .utils import get_logger, print_error, print_success, print_info
12
+
13
+ logger = get_logger(__name__)
14
+
15
+ # Import mock API for fallback
16
+ try:
17
+ from .mock_api import _mock_api
18
+ MOCK_AVAILABLE = True
19
+ except ImportError:
20
+ MOCK_AVAILABLE = False
21
+ _mock_api = None
22
+
23
+ # Keyring service name
24
+ KEYRING_SERVICE = "itcpr"
25
+ KEYRING_USERNAME = "device-token"
26
+
27
+ class Auth:
28
+ """Manages device authentication."""
29
+
30
+ def __init__(self):
31
+ self.api_base = config.api_base
32
+ self.device_id: Optional[str] = None
33
+ self.device_token: Optional[str] = None
34
+ self._load_token()
35
+
36
+ def _load_token(self):
37
+ """Load device token from keyring."""
38
+ try:
39
+ token = keyring.get_password(KEYRING_SERVICE, KEYRING_USERNAME)
40
+ if token:
41
+ # Token format: device_id:token
42
+ parts = token.split(":", 1)
43
+ if len(parts) == 2:
44
+ self.device_id, self.device_token = parts
45
+ logger.debug(f"Loaded device token for device: {self.device_id}")
46
+ except Exception as e:
47
+ logger.debug(f"Could not load token from keyring: {e}")
48
+ self.device_token = None
49
+ self.device_id = None
50
+
51
+ def is_authenticated(self) -> bool:
52
+ """Check if user is authenticated (has valid token)."""
53
+ if not self.device_token:
54
+ return False
55
+
56
+ # Optionally verify token is still valid on server
57
+ # This is a lightweight check - we'll do full validation when needed
58
+ return True
59
+
60
+ def verify_token(self) -> bool:
61
+ """Verify that the stored token is still valid on the server."""
62
+ if not self.device_token:
63
+ return False
64
+
65
+ try:
66
+ from .api import APIClient
67
+ api = APIClient(self)
68
+ return api.validate_token()
69
+ except Exception as e:
70
+ logger.debug(f"Token validation failed: {e}")
71
+ return False
72
+
73
+ def _get_device_name(self) -> str:
74
+ """Get device name (hostname)"""
75
+ try:
76
+ hostname = socket.gethostname()
77
+ # Try to get a more descriptive name on macOS
78
+ if platform.system() == 'Darwin': # macOS
79
+ try:
80
+ import subprocess
81
+ name = subprocess.check_output(['scutil', '--get', 'ComputerName'], text=True).strip()
82
+ if name:
83
+ return name
84
+ except:
85
+ pass
86
+ return hostname or 'Unknown Device'
87
+ except:
88
+ return 'Unknown Device'
89
+
90
+ def login(self) -> bool:
91
+ """Start device login flow."""
92
+ print_info("Starting device login flow...")
93
+
94
+ # Try real API first, fall back to mock on 404
95
+ use_mock = False
96
+ try:
97
+ # Step 1: Request device code
98
+ response = requests.post(
99
+ f"{self.api_base}/api/device/start",
100
+ json={},
101
+ timeout=10
102
+ )
103
+ response.raise_for_status()
104
+ data = response.json()
105
+ except requests.HTTPError as e:
106
+ # If 404 and mock is available, use mock
107
+ if e.response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
108
+ logger.info("Backend unavailable (404), using mock API")
109
+ print_info("⚠️ Backend unavailable, using mock mode for testing")
110
+ use_mock = True
111
+ data = _mock_api.device_start()
112
+ else:
113
+ raise
114
+ except requests.RequestException as e:
115
+ # Network error - try mock if available
116
+ if MOCK_AVAILABLE and _mock_api is not None and not config.mock_mode:
117
+ # Only use mock on network errors if explicitly enabled
118
+ raise
119
+ elif MOCK_AVAILABLE and _mock_api is not None:
120
+ logger.info("Network error, using mock API")
121
+ print_info("⚠️ Network error, using mock mode for testing")
122
+ use_mock = True
123
+ data = _mock_api.device_start()
124
+ else:
125
+ raise
126
+
127
+ device_code = data.get("device_code")
128
+ user_code = data.get("user_code")
129
+ # Frontend device page is at localhost (not cloud.itcpr.org or api.itcpr.org)
130
+ verification_uri = data.get("verification_uri", "http://localhost:5173/device")
131
+ # Always replace cloud.itcpr.org or api.itcpr.org with localhost for device page
132
+ if verification_uri:
133
+ if "cloud.itcpr.org" in verification_uri:
134
+ verification_uri = verification_uri.replace("cloud.itcpr.org", "localhost:5173")
135
+ if "api.itcpr.org" in verification_uri:
136
+ verification_uri = verification_uri.replace("api.itcpr.org", "localhost:5173")
137
+ # Ensure http (not https) for localhost
138
+ if verification_uri.startswith("https://"):
139
+ verification_uri = verification_uri.replace("https://", "http://")
140
+ expires_in = data.get("expires_in", 600)
141
+ interval = data.get("interval", 5)
142
+
143
+ # Format user code for display (e.g., ABCD-1234) to match web page
144
+ # Remove any existing hyphens first, then format
145
+ clean_code = user_code.replace('-', '')
146
+ if len(clean_code) == 8:
147
+ # Format as ABCD-1234 (4 chars, hyphen, 4 chars)
148
+ formatted_code = f"{clean_code[:4]}-{clean_code[4:]}"
149
+ else:
150
+ # If not 8 chars, just use as-is
151
+ formatted_code = user_code
152
+
153
+ print_info(f"\nDevice code: {formatted_code}")
154
+ print_info(f"Please visit: {verification_uri}")
155
+ print_info("\nWaiting for approval...")
156
+
157
+ # Open browser
158
+ try:
159
+ webbrowser.open(verification_uri)
160
+ except Exception as e:
161
+ logger.debug(f"Could not open browser: {e}")
162
+ print_info("Please open the URL manually in your browser.")
163
+
164
+ # Step 2: Poll for approval
165
+ start_time = time.time()
166
+ while time.time() - start_time < expires_in:
167
+ time.sleep(interval)
168
+
169
+ try:
170
+ if use_mock:
171
+ # Use mock API
172
+ token_data = _mock_api.device_poll(device_code)
173
+ if token_data is None:
174
+ print_info(".", end="", flush=True)
175
+ continue
176
+ else:
177
+ # Try real API
178
+ try:
179
+ # Get device name for header
180
+ device_name = self._get_device_name()
181
+ poll_response = requests.get(
182
+ f"{self.api_base}/api/device/poll",
183
+ params={"device_code": device_code},
184
+ headers={"X-Device-Name": device_name},
185
+ timeout=10
186
+ )
187
+
188
+ if poll_response.status_code == 200:
189
+ token_data = poll_response.json()
190
+ elif poll_response.status_code == 202:
191
+ # Still waiting
192
+ print_info(".", end="", flush=True)
193
+ continue
194
+ elif poll_response.status_code == 400:
195
+ error_data = poll_response.json()
196
+ error = error_data.get("error", "Unknown error")
197
+ print_error(f"Authentication failed: {error}")
198
+ return False
199
+ elif poll_response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
200
+ # Backend unavailable, switch to mock
201
+ logger.info("Backend unavailable (404), switching to mock API")
202
+ use_mock = True
203
+ token_data = _mock_api.device_poll(device_code)
204
+ if token_data is None:
205
+ print_info(".", end="", flush=True)
206
+ continue
207
+ else:
208
+ continue
209
+ except requests.HTTPError as e:
210
+ if e.response.status_code == 404 and MOCK_AVAILABLE and _mock_api is not None:
211
+ # Switch to mock
212
+ use_mock = True
213
+ token_data = _mock_api.device_poll(device_code)
214
+ if token_data is None:
215
+ print_info(".", end="", flush=True)
216
+ continue
217
+ else:
218
+ raise
219
+
220
+ device_id = token_data.get("device_id")
221
+ device_token = token_data.get("device_token")
222
+
223
+ if device_id and device_token:
224
+ # Store token
225
+ self.device_id = device_id
226
+ self.device_token = device_token
227
+ self._save_token()
228
+ if use_mock:
229
+ print_success("Device authenticated successfully! (Mock mode)")
230
+ else:
231
+ print_success("Device authenticated successfully!")
232
+ return True
233
+
234
+ except requests.RequestException as e:
235
+ logger.debug(f"Poll request failed: {e}")
236
+ if use_mock:
237
+ # Try mock
238
+ token_data = _mock_api.device_poll(device_code)
239
+ if token_data:
240
+ device_id = token_data.get("device_id")
241
+ device_token = token_data.get("device_token")
242
+ if device_id and device_token:
243
+ self.device_id = device_id
244
+ self.device_token = device_token
245
+ self._save_token()
246
+ print_success("Device authenticated successfully! (Mock mode)")
247
+ return True
248
+ print_info(".", end="", flush=True)
249
+ continue
250
+
251
+ print_error("Authentication timed out. Please try again.")
252
+ return False
253
+
254
+ def _save_token(self):
255
+ """Save device token to keyring."""
256
+ if self.device_id and self.device_token:
257
+ try:
258
+ token_string = f"{self.device_id}:{self.device_token}"
259
+ keyring.set_password(KEYRING_SERVICE, KEYRING_USERNAME, token_string)
260
+ logger.debug("Token saved to keyring")
261
+ except Exception as e:
262
+ logger.error(f"Failed to save token to keyring: {e}")
263
+ raise
264
+
265
+ def logout(self):
266
+ """Logout and clear stored token."""
267
+ if self.device_token:
268
+ try:
269
+ # Revoke token on server
270
+ requests.post(
271
+ f"{self.api_base}/api/device/revoke",
272
+ json={"device_id": self.device_id},
273
+ headers={"Authorization": f"Bearer {self.device_token}"},
274
+ timeout=10
275
+ )
276
+ except Exception as e:
277
+ logger.debug(f"Could not revoke token on server: {e}")
278
+
279
+ # Clear local token
280
+ try:
281
+ keyring.delete_password(KEYRING_SERVICE, KEYRING_USERNAME)
282
+ except Exception as e:
283
+ logger.debug(f"Could not delete token from keyring: {e}")
284
+
285
+ self.device_token = None
286
+ self.device_id = None
287
+ print_success("Logged out successfully")
288
+
289
+ def get_token(self) -> Optional[str]:
290
+ """Get current device token."""
291
+ return self.device_token
292
+
293
+ def get_device_id(self) -> Optional[str]:
294
+ """Get current device ID."""
295
+ return self.device_id
296
+
@@ -17,12 +17,20 @@ def cli(ctx, verbose):
17
17
 
18
18
  @cli.command()
19
19
  def login():
20
- """Authenticate this device with cloud.itcpr.org."""
20
+ """Authenticate this device with ITCPR Cloud."""
21
21
  from .auth import Auth
22
22
  auth = Auth()
23
23
  if auth.is_authenticated():
24
- if not click.confirm("You are already logged in. Do you want to login again?"):
25
- return
24
+ # Verify token is still valid
25
+ if auth.verify_token():
26
+ if not click.confirm("You are already logged in. Do you want to login again?"):
27
+ return
28
+ else:
29
+ # Token exists but is invalid (device was revoked)
30
+ click.echo("Your device token is no longer valid (device may have been removed).")
31
+ click.echo("Logging in again...")
32
+ # Clear invalid token
33
+ auth.logout()
26
34
 
27
35
  success = auth.login()
28
36
  if not success:
@@ -190,9 +198,8 @@ def clone(ctx, repo, path):
190
198
  if path:
191
199
  local_path = Path(path)
192
200
  else:
193
- # Default: clone to ~/itcpr-repos/{name}
194
- default_dir = Path.home() / "itcpr-repos"
195
- local_path = default_dir / repo_name
201
+ # Default: clone to current working directory
202
+ local_path = Path.cwd() / repo_name
196
203
 
197
204
  # Check if already cloned
198
205
  existing = storage.get_repo(repo_name)
@@ -19,7 +19,7 @@ CONFIG_FILE = CONFIG_DIR / "config.toml"
19
19
  DB_FILE = CONFIG_DIR / "repos.db"
20
20
 
21
21
  # Default API endpoint
22
- DEFAULT_API_BASE = "https://cloud.itcpr.org"
22
+ DEFAULT_API_BASE = "https://api.itcpr.org"
23
23
 
24
24
  class Config:
25
25
  """Manages application configuration."""
@@ -29,8 +29,13 @@ class Config:
29
29
  self.config_file = CONFIG_FILE
30
30
  self.db_file = DB_FILE
31
31
  self.api_base = os.getenv("ITCPR_API_BASE", DEFAULT_API_BASE)
32
+ # Enable mock mode if explicitly set or if backend is unavailable
33
+ self.mock_mode = os.getenv("ITCPR_MOCK_MODE", "").lower() in ("true", "1", "yes")
32
34
  self._config_data: Dict[str, Any] = {}
33
35
  self._load_config()
36
+ # Check config file for mock mode
37
+ if not self.mock_mode:
38
+ self.mock_mode = self.get("mock_mode", False)
34
39
 
35
40
  def _load_config(self):
36
41
  """Load configuration from file."""
@@ -17,15 +17,18 @@ class GitOps:
17
17
  if not self.git:
18
18
  raise RuntimeError("git command not found. Please install git.")
19
19
 
20
- def _run_git(self, *args, check: bool = True, capture_output: bool = True) -> subprocess.CompletedProcess:
20
+ def _run_git(self, *args, check: bool = True, capture_output: bool = True, cwd: Optional[Path] = None) -> subprocess.CompletedProcess:
21
21
  """Run git command."""
22
22
  cmd = [self.git] + list(args)
23
- logger.debug(f"Running: {' '.join(cmd)} in {self.repo_path}")
23
+ working_dir = cwd if cwd else self.repo_path
24
+ # Convert Path to string for cwd
25
+ cwd_str = str(working_dir) if working_dir else None
26
+ logger.debug(f"Running: {' '.join(cmd)} in {cwd_str}")
24
27
 
25
28
  try:
26
29
  result = subprocess.run(
27
30
  cmd,
28
- cwd=self.repo_path,
31
+ cwd=cwd_str,
29
32
  check=check,
30
33
  capture_output=capture_output,
31
34
  text=True,
@@ -52,17 +55,35 @@ class GitOps:
52
55
  if token:
53
56
  # Insert token into URL
54
57
  if remote_url.startswith("https://"):
55
- # https://github.com/owner/repo.git -> https://token@github.com/owner/repo.git
58
+ # GitHub App installation tokens need x-access-token: prefix
59
+ # https://github.com/owner/repo.git -> https://x-access-token:TOKEN@github.com/owner/repo.git
56
60
  url_parts = remote_url.split("://", 1)
57
- remote_url = f"{url_parts[0]}://{token}@{url_parts[1]}"
61
+ remote_url = f"{url_parts[0]}://x-access-token:{token}@{url_parts[1]}"
58
62
  elif remote_url.startswith("git@"):
59
63
  # For SSH, we'd need to use GIT_SSH_COMMAND, but we'll use HTTPS with token
60
- pass
64
+ # Convert SSH URL to HTTPS with token
65
+ # git@github.com:owner/repo.git -> https://x-access-token:TOKEN@github.com/owner/repo.git
66
+ ssh_parts = remote_url.replace("git@", "").replace(":", "/", 1)
67
+ remote_url = f"https://x-access-token:{token}@{ssh_parts}"
61
68
 
62
69
  try:
63
- self.repo_path.parent.mkdir(parents=True, exist_ok=True)
64
- self._run_git("clone", remote_url, str(self.repo_path), check=True)
65
- logger.info(f"Cloned repository to {self.repo_path}")
70
+ # Ensure parent directory exists
71
+ parent_dir = self.repo_path.parent
72
+ parent_dir.mkdir(parents=True, exist_ok=True)
73
+
74
+ # Git clone needs to be run from the parent directory
75
+ # Clone to the repo name in the parent directory
76
+ repo_name = self.repo_path.name
77
+
78
+ # Run git clone from parent directory
79
+ self._run_git("clone", remote_url, repo_name, check=True, cwd=parent_dir)
80
+
81
+ # Verify the clone was successful
82
+ cloned_path = parent_dir / repo_name
83
+ if not cloned_path.exists():
84
+ raise RuntimeError(f"Clone completed but repository not found at {cloned_path}")
85
+
86
+ logger.info(f"Cloned repository to {cloned_path}")
66
87
  return True
67
88
  except Exception as e:
68
89
  logger.error(f"Clone failed: {e}")
@@ -90,19 +111,44 @@ class GitOps:
90
111
  status_result = self._run_git("status", "--porcelain", check=True)
91
112
  has_changes = bool(status_result.stdout.strip())
92
113
 
93
- # Check if there are unpushed commits
94
- try:
95
- self._run_git("rev-list", "--count", "HEAD..origin/HEAD", check=True)
96
- behind = True
97
- except:
98
- behind = False
114
+ # Get current branch
115
+ current_branch_result = self._run_git("rev-parse", "--abbrev-ref", "HEAD", check=True)
116
+ current_branch = current_branch_result.stdout.strip()
99
117
 
100
- # Check if there are remote changes
118
+ # Get remote tracking branch (e.g., origin/main)
119
+ remote_branch = None
101
120
  try:
102
- self._run_git("rev-list", "--count", "origin/HEAD..HEAD", check=True)
103
- ahead = True
121
+ remote_result = self._run_git("rev-parse", "--abbrev-ref", f"{current_branch}@{{upstream}}", check=True)
122
+ remote_branch = remote_result.stdout.strip()
104
123
  except:
105
- ahead = False
124
+ # No upstream branch set, try origin/{current_branch}
125
+ remote_branch = f"origin/{current_branch}"
126
+
127
+ # Check if there are remote commits to pull (behind)
128
+ behind = False
129
+ if remote_branch:
130
+ try:
131
+ # Check if remote branch exists
132
+ self._run_git("rev-parse", "--verify", remote_branch, check=True)
133
+ # Count commits in remote that aren't in local
134
+ behind_result = self._run_git("rev-list", "--count", f"HEAD..{remote_branch}", check=True)
135
+ behind_count = int(behind_result.stdout.strip())
136
+ behind = behind_count > 0
137
+ except:
138
+ behind = False
139
+
140
+ # Check if there are local commits to push (ahead)
141
+ ahead = False
142
+ if remote_branch:
143
+ try:
144
+ # Check if remote branch exists
145
+ self._run_git("rev-parse", "--verify", remote_branch, check=True)
146
+ # Count commits in local that aren't in remote
147
+ ahead_result = self._run_git("rev-list", "--count", f"{remote_branch}..HEAD", check=True)
148
+ ahead_count = int(ahead_result.stdout.strip())
149
+ ahead = ahead_count > 0
150
+ except:
151
+ ahead = False
106
152
 
107
153
  return {
108
154
  "clean": not has_changes,
@@ -112,14 +112,16 @@ class SyncManager:
112
112
  "error": "Uncommitted changes detected and auto_commit is disabled in itcpr.yml"
113
113
  }
114
114
 
115
- # Fetch latest
116
- print_info(f" Fetching latest changes...")
115
+ # Fetch latest (silently, to update remote refs)
117
116
  git.fetch()
118
117
 
119
- # Check for conflicts before pulling
118
+ # Check status after fetch
120
119
  status = git.get_status()
121
- if status.get("behind"):
122
- # Pull with rebase
120
+ is_behind = status.get("behind", False)
121
+ is_ahead = status.get("ahead", False)
122
+
123
+ # Pull if behind
124
+ if is_behind:
123
125
  try:
124
126
  print_info(f" Pulling changes...")
125
127
  git.pull_rebase()
@@ -133,7 +135,7 @@ class SyncManager:
133
135
  raise
134
136
 
135
137
  # Push if ahead (check auto_push rule)
136
- if status.get("ahead"):
138
+ if is_ahead:
137
139
  if rules.get('auto_push', True):
138
140
  print_info(f" Pushing local commits...")
139
141
  try:
@@ -148,6 +150,10 @@ class SyncManager:
148
150
  logger.info(f"Push skipped for {repo_name} (auto_push disabled in itcpr.yml)")
149
151
  print_info(f" Local commits not pushed (auto_push disabled)")
150
152
 
153
+ # If no changes, just log silently (no output to user)
154
+ if not is_behind and not is_ahead:
155
+ logger.debug(f"Repository {repo_name} is up to date")
156
+
151
157
  # Update sync time
152
158
  self.storage.update_sync_time(repo_name)
153
159
  self.storage.add_sync_history(repo_name, "success", "Sync completed")
@@ -25,9 +25,9 @@ def print_success(message: str):
25
25
  """Print success message."""
26
26
  print(f"✓ {message}")
27
27
 
28
- def print_info(message: str):
28
+ def print_info(message: str, end: str = "\n", flush: bool = False):
29
29
  """Print info message."""
30
- print(message)
30
+ print(message, end=end, flush=flush)
31
31
 
32
32
  def format_duration(seconds: float) -> str:
33
33
  """Format duration in human-readable format."""
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: itcpr
3
- Version: 2.0.7
3
+ Version: 2.0.8
4
4
  Summary: CLI tool for syncing GitHub repositories from ITCPR Cloud
5
5
  Home-page: https://itcpr.org
6
6
  Author: ITCPR
@@ -38,7 +38,7 @@ A production-ready CLI tool for syncing GitHub repositories from ITCPR Cloud to
38
38
 
39
39
  ## Features
40
40
 
41
- - 🔐 Device-based authentication with cloud.itcpr.org
41
+ - 🔐 Device-based authentication with ITCPR Cloud
42
42
  - 📦 Automatic repository synchronization
43
43
  - 🔄 Manual or continuous sync modes
44
44
  - 💾 Local SQLite database for metadata tracking
@@ -107,7 +107,7 @@ rm -rf ~/.itcpr
107
107
 
108
108
  - Python 3.10+
109
109
  - Git (system installation)
110
- - Access to cloud.itcpr.org
110
+ - Access to api.itcpr.org (API) and cloud.itcpr.org (frontend)
111
111
 
112
112
  ## Quick Start
113
113
 
@@ -187,7 +187,7 @@ itcpr logout
187
187
 
188
188
  ### `itcpr login`
189
189
 
190
- Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls for approval.
190
+ Starts device authentication flow. Opens browser to `cloud.itcpr.org/device` and polls the API at `api.itcpr.org` for approval.
191
191
 
192
192
  ### `itcpr logout`
193
193
 
@@ -304,11 +304,37 @@ pip install itcpr[yaml]
304
304
  pip install PyYAML
305
305
  ```
306
306
 
307
+ ## Development / Mock Mode
308
+
309
+ When the API at `api.itcpr.org` is unavailable, the CLI automatically falls back to mock API responses for testing and development.
310
+
311
+ **Automatic Mock Mode:**
312
+ - If the backend returns 404 or is unreachable, mock responses are used automatically
313
+ - You'll see a warning: "⚠️ Backend unavailable, using mock mode for testing"
314
+
315
+ **Manual Mock Mode:**
316
+ You can also enable mock mode explicitly:
317
+
318
+ ```bash
319
+ # Using environment variable
320
+ export ITCPR_MOCK_MODE=true
321
+ itcpr login
322
+
323
+ # Or set in config file (~/.itcpr/config.toml)
324
+ # mock_mode = true
325
+ ```
326
+
327
+ **Mock Features:**
328
+ - Auto-approves device login after 2 seconds
329
+ - Provides sample user and repository data
330
+ - Generates mock GitHub tokens
331
+ - All commands work in mock mode for testing
332
+
307
333
  ## Troubleshooting
308
334
 
309
335
  ### "Not logged in" error
310
336
 
311
- Run `itcpr login` to authenticate your device.
337
+ Run `itcpr login` to authenticate your device. If the backend is unavailable, mock mode will activate automatically.
312
338
 
313
339
  ### "Repository not assigned" error
314
340
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "itcpr"
7
- version = "2.0.7"
7
+ version = "2.0.8"
8
8
  description = "CLI tool for syncing GitHub repositories from ITCPR Cloud"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
@@ -9,7 +9,7 @@ long_description = readme_file.read_text() if readme_file.exists() else ""
9
9
 
10
10
  setup(
11
11
  name="itcpr",
12
- version="2.0.7",
12
+ version="2.0.8",
13
13
  description="CLI tool for syncing GitHub repositories from ITCPR Cloud",
14
14
  long_description=long_description,
15
15
  long_description_content_type="text/markdown",
itcpr-2.0.7/LICENSE DELETED
@@ -1,22 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 ITCPR
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
22
-
itcpr-2.0.7/itcpr/api.py DELETED
@@ -1,73 +0,0 @@
1
- """API client for cloud.itcpr.org."""
2
-
3
- import requests
4
- from typing import List, Dict, Any, Optional
5
- from .auth import Auth
6
- from .utils import get_logger, print_error
7
-
8
- logger = get_logger(__name__)
9
-
10
- class APIClient:
11
- """Client for ITCPR Cloud API."""
12
-
13
- def __init__(self, auth: Auth):
14
- self.auth = auth
15
- self.api_base = auth.api_base
16
-
17
- def _get_headers(self) -> Dict[str, str]:
18
- """Get request headers with authentication."""
19
- headers = {"Content-Type": "application/json"}
20
- token = self.auth.get_token()
21
- if token:
22
- headers["Authorization"] = f"Bearer {token}"
23
- return headers
24
-
25
- def _request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
26
- """Make authenticated API request."""
27
- url = f"{self.api_base}{endpoint}"
28
- headers = self._get_headers()
29
- headers.update(kwargs.pop("headers", {}))
30
-
31
- try:
32
- response = requests.request(method, url, headers=headers, timeout=30, **kwargs)
33
- return response
34
- except requests.RequestException as e:
35
- logger.error(f"API request failed: {e}")
36
- raise
37
-
38
- def get_me(self) -> Dict[str, Any]:
39
- """Get current user/device information."""
40
- response = self._request("GET", "/api/agent/me")
41
- response.raise_for_status()
42
- return response.json()
43
-
44
- def get_repos(self) -> List[Dict[str, Any]]:
45
- """Get list of assigned repositories."""
46
- response = self._request("GET", "/api/agent/repos")
47
- response.raise_for_status()
48
- data = response.json()
49
- return data.get("repos", [])
50
-
51
- def get_github_token(self, repo_name: Optional[str] = None) -> str:
52
- """Get short-lived GitHub installation token."""
53
- payload = {}
54
- if repo_name:
55
- payload["repo"] = repo_name
56
-
57
- response = self._request("POST", "/api/agent/token", json=payload)
58
- response.raise_for_status()
59
- data = response.json()
60
- return data.get("token")
61
-
62
- def validate_token(self) -> bool:
63
- """Validate current device token."""
64
- try:
65
- self.get_me()
66
- return True
67
- except requests.HTTPError as e:
68
- if e.response.status_code == 401:
69
- return False
70
- raise
71
- except Exception:
72
- return False
73
-
itcpr-2.0.7/itcpr/auth.py DELETED
@@ -1,167 +0,0 @@
1
- """Authentication management for ITCPR Agent."""
2
-
3
- import keyring
4
- import time
5
- import webbrowser
6
- import requests
7
- from typing import Optional, Dict, Any
8
- from .config import config
9
- from .utils import get_logger, print_error, print_success, print_info
10
-
11
- logger = get_logger(__name__)
12
-
13
- # Keyring service name
14
- KEYRING_SERVICE = "itcpr"
15
- KEYRING_USERNAME = "device-token"
16
-
17
- class Auth:
18
- """Manages device authentication."""
19
-
20
- def __init__(self):
21
- self.api_base = config.api_base
22
- self.device_id: Optional[str] = None
23
- self.device_token: Optional[str] = None
24
- self._load_token()
25
-
26
- def _load_token(self):
27
- """Load device token from keyring."""
28
- try:
29
- token = keyring.get_password(KEYRING_SERVICE, KEYRING_USERNAME)
30
- if token:
31
- # Token format: device_id:token
32
- parts = token.split(":", 1)
33
- if len(parts) == 2:
34
- self.device_id, self.device_token = parts
35
- logger.debug(f"Loaded device token for device: {self.device_id}")
36
- except Exception as e:
37
- logger.debug(f"Could not load token from keyring: {e}")
38
- self.device_token = None
39
- self.device_id = None
40
-
41
- def is_authenticated(self) -> bool:
42
- """Check if user is authenticated."""
43
- return self.device_token is not None
44
-
45
- def login(self) -> bool:
46
- """Start device login flow."""
47
- print_info("Starting device login flow...")
48
-
49
- try:
50
- # Step 1: Request device code
51
- response = requests.post(
52
- f"{self.api_base}/api/device/start",
53
- json={},
54
- timeout=10
55
- )
56
- response.raise_for_status()
57
- data = response.json()
58
-
59
- device_code = data.get("device_code")
60
- user_code = data.get("user_code")
61
- verification_uri = data.get("verification_uri", f"{self.api_base}/device")
62
- expires_in = data.get("expires_in", 600)
63
- interval = data.get("interval", 5)
64
-
65
- print_info(f"\nDevice code: {user_code}")
66
- print_info(f"Please visit: {verification_uri}")
67
- print_info("\nWaiting for approval...")
68
-
69
- # Open browser
70
- try:
71
- webbrowser.open(verification_uri)
72
- except Exception as e:
73
- logger.debug(f"Could not open browser: {e}")
74
- print_info("Please open the URL manually in your browser.")
75
-
76
- # Step 2: Poll for approval
77
- start_time = time.time()
78
- while time.time() - start_time < expires_in:
79
- time.sleep(interval)
80
-
81
- try:
82
- poll_response = requests.get(
83
- f"{self.api_base}/api/device/poll",
84
- params={"device_code": device_code},
85
- timeout=10
86
- )
87
-
88
- if poll_response.status_code == 200:
89
- token_data = poll_response.json()
90
- device_id = token_data.get("device_id")
91
- device_token = token_data.get("device_token")
92
-
93
- if device_id and device_token:
94
- # Store token
95
- self.device_id = device_id
96
- self.device_token = device_token
97
- self._save_token()
98
- print_success("Device authenticated successfully!")
99
- return True
100
-
101
- elif poll_response.status_code == 202:
102
- # Still waiting
103
- print_info(".", end="", flush=True)
104
- continue
105
-
106
- elif poll_response.status_code == 400:
107
- error_data = poll_response.json()
108
- error = error_data.get("error", "Unknown error")
109
- print_error(f"Authentication failed: {error}")
110
- return False
111
-
112
- except requests.RequestException as e:
113
- logger.debug(f"Poll request failed: {e}")
114
- print_info(".", end="", flush=True)
115
- continue
116
-
117
- print_error("Authentication timed out. Please try again.")
118
- return False
119
-
120
- except requests.RequestException as e:
121
- print_error(f"Failed to start login: {e}")
122
- logger.exception("Login error")
123
- return False
124
-
125
- def _save_token(self):
126
- """Save device token to keyring."""
127
- if self.device_id and self.device_token:
128
- try:
129
- token_string = f"{self.device_id}:{self.device_token}"
130
- keyring.set_password(KEYRING_SERVICE, KEYRING_USERNAME, token_string)
131
- logger.debug("Token saved to keyring")
132
- except Exception as e:
133
- logger.error(f"Failed to save token to keyring: {e}")
134
- raise
135
-
136
- def logout(self):
137
- """Logout and clear stored token."""
138
- if self.device_token:
139
- try:
140
- # Revoke token on server
141
- requests.post(
142
- f"{self.api_base}/api/device/revoke",
143
- json={"device_id": self.device_id},
144
- headers={"Authorization": f"Bearer {self.device_token}"},
145
- timeout=10
146
- )
147
- except Exception as e:
148
- logger.debug(f"Could not revoke token on server: {e}")
149
-
150
- # Clear local token
151
- try:
152
- keyring.delete_password(KEYRING_SERVICE, KEYRING_USERNAME)
153
- except Exception as e:
154
- logger.debug(f"Could not delete token from keyring: {e}")
155
-
156
- self.device_token = None
157
- self.device_id = None
158
- print_success("Logged out successfully")
159
-
160
- def get_token(self) -> Optional[str]:
161
- """Get current device token."""
162
- return self.device_token
163
-
164
- def get_device_id(self) -> Optional[str]:
165
- """Get current device ID."""
166
- return self.device_id
167
-
File without changes
File without changes
File without changes
File without changes
File without changes