resulgit 1.0.4 → 1.0.6

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.
package/lib/blame.js ADDED
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Git Blame Implementation
3
+ * Shows line-by-line authorship information for files
4
+ */
5
+
6
+ /**
7
+ * Parse blame data from commit history
8
+ */
9
+ function parseBlame(fileContent, commits, filePath) {
10
+ const lines = fileContent.split(/\r?\n/)
11
+ const blameData = []
12
+
13
+ // For simplicity, we'll attribute all lines to the most recent commit
14
+ // In a full implementation, we'd track line-by-line changes through history
15
+ const latestCommit = commits.length > 0 ? commits[0] : null
16
+
17
+ for (let i = 0; i < lines.length; i++) {
18
+ blameData.push({
19
+ lineNumber: i + 1,
20
+ commitId: latestCommit?.id || latestCommit?._id || 'uncommitted',
21
+ author: latestCommit?.author?.name || 'Unknown',
22
+ authorEmail: latestCommit?.author?.email || '',
23
+ date: latestCommit?.createdAt || latestCommit?.committer?.date || new Date().toISOString(),
24
+ content: lines[i]
25
+ })
26
+ }
27
+
28
+ return blameData
29
+ }
30
+
31
+ /**
32
+ * Format blame output for terminal
33
+ */
34
+ function formatBlameOutput(blameData, options = {}) {
35
+ const { colors = true } = options
36
+ const COLORS = {
37
+ reset: '\x1b[0m',
38
+ dim: '\x1b[2m',
39
+ cyan: '\x1b[36m',
40
+ yellow: '\x1b[33m',
41
+ green: '\x1b[32m'
42
+ }
43
+
44
+ const lines = []
45
+ const maxLineNum = String(blameData.length).length
46
+
47
+ for (const line of blameData) {
48
+ const lineNum = String(line.lineNumber).padStart(maxLineNum, ' ')
49
+ const commitShort = line.commitId.slice(0, 8)
50
+ const author = line.author.slice(0, 20).padEnd(20, ' ')
51
+ const date = new Date(line.date).toISOString().split('T')[0]
52
+
53
+ if (colors) {
54
+ const formatted = `${COLORS.dim}${lineNum}${COLORS.reset} ` +
55
+ `${COLORS.yellow}${commitShort}${COLORS.reset} ` +
56
+ `${COLORS.cyan}${author}${COLORS.reset} ` +
57
+ `${COLORS.green}${date}${COLORS.reset} ` +
58
+ `${line.content}`
59
+ lines.push(formatted)
60
+ } else {
61
+ lines.push(`${lineNum} ${commitShort} ${author} ${date} ${line.content}`)
62
+ }
63
+ }
64
+
65
+ return lines.join('\n')
66
+ }
67
+
68
+ /**
69
+ * Format blame output as JSON
70
+ */
71
+ function formatBlameJson(blameData) {
72
+ return JSON.stringify(blameData, null, 2)
73
+ }
74
+
75
+ module.exports = {
76
+ parseBlame,
77
+ formatBlameOutput,
78
+ formatBlameJson
79
+ }
package/lib/errors.js ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Custom Error Classes for ResulGit
3
+ * Provides specific error types for better error handling and user feedback
4
+ */
5
+
6
+ /**
7
+ * Base error class for ResulGit
8
+ */
9
+ class ResulGitError extends Error {
10
+ constructor(message, code, details = {}) {
11
+ super(message)
12
+ this.name = 'ResulGitError'
13
+ this.code = code
14
+ this.details = details
15
+ Error.captureStackTrace(this, this.constructor)
16
+ }
17
+
18
+ toJSON() {
19
+ return {
20
+ error: this.name,
21
+ code: this.code,
22
+ message: this.message,
23
+ details: this.details
24
+ }
25
+ }
26
+ }
27
+
28
+ /**
29
+ * Validation error
30
+ */
31
+ class ValidationError extends ResulGitError {
32
+ constructor(message, field) {
33
+ super(message, 'VALIDATION_ERROR', { field })
34
+ this.name = 'ValidationError'
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Authentication error
40
+ */
41
+ class AuthenticationError extends ResulGitError {
42
+ constructor(message) {
43
+ super(message, 'AUTH_ERROR')
44
+ this.name = 'AuthenticationError'
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Repository not found error
50
+ */
51
+ class RepositoryNotFoundError extends ResulGitError {
52
+ constructor(repoId) {
53
+ super(`Repository not found: ${repoId}`, 'REPO_NOT_FOUND', { repoId })
54
+ this.name = 'RepositoryNotFoundError'
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Branch not found error
60
+ */
61
+ class BranchNotFoundError extends ResulGitError {
62
+ constructor(branchName, repoId) {
63
+ super(`Branch not found: ${branchName}`, 'BRANCH_NOT_FOUND', { branchName, repoId })
64
+ this.name = 'BranchNotFoundError'
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Commit not found error
70
+ */
71
+ class CommitNotFoundError extends ResulGitError {
72
+ constructor(commitId) {
73
+ super(`Commit not found: ${commitId}`, 'COMMIT_NOT_FOUND', { commitId })
74
+ this.name = 'CommitNotFoundError'
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Merge conflict error
80
+ */
81
+ class ConflictError extends ResulGitError {
82
+ constructor(conflicts) {
83
+ const fileList = conflicts.map(c => c.path).join(', ')
84
+ super(`Merge conflicts in files: ${fileList}`, 'MERGE_CONFLICT', { conflicts })
85
+ this.name = 'ConflictError'
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Network error
91
+ */
92
+ class NetworkError extends ResulGitError {
93
+ constructor(message, statusCode, url) {
94
+ super(message, 'NETWORK_ERROR', { statusCode, url })
95
+ this.name = 'NetworkError'
96
+ }
97
+ }
98
+
99
+ /**
100
+ * File system error
101
+ */
102
+ class FileSystemError extends ResulGitError {
103
+ constructor(message, path, operation) {
104
+ super(message, 'FS_ERROR', { path, operation })
105
+ this.name = 'FileSystemError'
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Configuration error
111
+ */
112
+ class ConfigurationError extends ResulGitError {
113
+ constructor(message, configKey) {
114
+ super(message, 'CONFIG_ERROR', { configKey })
115
+ this.name = 'ConfigurationError'
116
+ }
117
+ }
118
+
119
+ /**
120
+ * Remote repository error
121
+ */
122
+ class RemoteError extends ResulGitError {
123
+ constructor(message) {
124
+ super(message, 'REMOTE_ERROR')
125
+ this.name = 'RemoteError'
126
+ }
127
+ }
128
+
129
+ /**
130
+ * Format error for display
131
+ */
132
+ function formatError(err, jsonMode = false) {
133
+ if (jsonMode) {
134
+ if (err instanceof ResulGitError) {
135
+ return JSON.stringify(err.toJSON(), null, 2)
136
+ }
137
+ return JSON.stringify({
138
+ error: 'Error',
139
+ message: err.message,
140
+ code: err.code || 'UNKNOWN_ERROR'
141
+ }, null, 2)
142
+ }
143
+
144
+ // Colorized output for terminal
145
+ const COLORS = {
146
+ red: '\x1b[31m',
147
+ yellow: '\x1b[33m',
148
+ reset: '\x1b[0m',
149
+ bold: '\x1b[1m'
150
+ }
151
+
152
+ let output = `${COLORS.bold}${COLORS.red}Error:${COLORS.reset} ${err.message}\n`
153
+
154
+ if (err instanceof ResulGitError && err.code) {
155
+ output += `${COLORS.yellow}Code:${COLORS.reset} ${err.code}\n`
156
+ }
157
+
158
+ if (err instanceof ConflictError && err.details.conflicts) {
159
+ output += `${COLORS.yellow}Conflicts:${COLORS.reset}\n`
160
+ for (const conflict of err.details.conflicts) {
161
+ output += ` - ${conflict.path}${conflict.line ? `:${conflict.line}` : ''}\n`
162
+ }
163
+ }
164
+
165
+ return output
166
+ }
167
+
168
+ /**
169
+ * Wrap async function with error handling
170
+ */
171
+ function wrapAsync(fn) {
172
+ return async function (...args) {
173
+ try {
174
+ return await fn(...args)
175
+ } catch (err) {
176
+ if (err instanceof ResulGitError) {
177
+ throw err
178
+ }
179
+
180
+ // Convert common errors to ResulGit errors
181
+ if (err.code === 'ENOENT') {
182
+ throw new FileSystemError(`File or directory not found: ${err.path}`, err.path, 'read')
183
+ }
184
+
185
+ if (err.code === 'EACCES') {
186
+ throw new FileSystemError(`Permission denied: ${err.path}`, err.path, 'access')
187
+ }
188
+
189
+ if (err.message && err.message.includes('fetch failed')) {
190
+ throw new NetworkError(err.message, null, null)
191
+ }
192
+
193
+ // Re-throw unknown errors
194
+ throw err
195
+ }
196
+ }
197
+ }
198
+
199
+ module.exports = {
200
+ ResulGitError,
201
+ ValidationError,
202
+ AuthenticationError,
203
+ RepositoryNotFoundError,
204
+ BranchNotFoundError,
205
+ CommitNotFoundError,
206
+ ConflictError,
207
+ NetworkError,
208
+ FileSystemError,
209
+ ConfigurationError,
210
+ RemoteError,
211
+ formatError,
212
+ wrapAsync
213
+ }
package/lib/hooks.js ADDED
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Git Hooks System
3
+ * Allows execution of custom scripts at specific points in the Git workflow
4
+ */
5
+
6
+ const fs = require('fs').promises
7
+ const path = require('path')
8
+ const { exec } = require('child_process')
9
+ const util = require('util')
10
+ const execPromise = util.promisify(exec)
11
+
12
+ /**
13
+ * Available hook types
14
+ */
15
+ const HOOK_TYPES = [
16
+ 'pre-commit',
17
+ 'post-commit',
18
+ 'pre-push',
19
+ 'post-push',
20
+ 'pre-merge',
21
+ 'post-merge',
22
+ 'pre-checkout',
23
+ 'post-checkout'
24
+ ]
25
+
26
+ /**
27
+ * Get hooks directory path
28
+ */
29
+ function getHooksDir(repoDir) {
30
+ return path.join(repoDir, '.git', 'hooks')
31
+ }
32
+
33
+ /**
34
+ * Check if a hook exists
35
+ */
36
+ async function hookExists(repoDir, hookName) {
37
+ if (!HOOK_TYPES.includes(hookName)) {
38
+ throw new Error(`Invalid hook type: ${hookName}. Valid types: ${HOOK_TYPES.join(', ')}`)
39
+ }
40
+
41
+ const hooksDir = getHooksDir(repoDir)
42
+ const hookPath = path.join(hooksDir, hookName)
43
+
44
+ try {
45
+ const stat = await fs.stat(hookPath)
46
+ return stat.isFile()
47
+ } catch {
48
+ return false
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Execute a hook
54
+ */
55
+ async function executeHook(repoDir, hookName, context = {}) {
56
+ if (!await hookExists(repoDir, hookName)) {
57
+ return { executed: false, output: null, error: null }
58
+ }
59
+
60
+ const hookPath = path.join(getHooksDir(repoDir), hookName)
61
+
62
+ try {
63
+ // Check if file is executable
64
+ const stat = await fs.stat(hookPath)
65
+ const isExecutable = (stat.mode & 0o111) !== 0
66
+
67
+ if (!isExecutable) {
68
+ return { executed: false, output: null, error: 'Hook is not executable' }
69
+ }
70
+
71
+ // Pass context as environment variables
72
+ const env = {
73
+ ...process.env,
74
+ RESULGIT_HOOK: hookName,
75
+ RESULGIT_REPO_DIR: repoDir,
76
+ ...Object.fromEntries(
77
+ Object.entries(context).map(([k, v]) => [`RESULGIT_${k.toUpperCase()}`, String(v)])
78
+ )
79
+ }
80
+
81
+ // Execute the hook
82
+ const { stdout, stderr } = await execPromise(hookPath, {
83
+ cwd: repoDir,
84
+ env,
85
+ timeout: 60000 // 60 second timeout
86
+ })
87
+
88
+ return {
89
+ executed: true,
90
+ output: stdout,
91
+ error: stderr || null,
92
+ exitCode: 0
93
+ }
94
+ } catch (err) {
95
+ return {
96
+ executed: true,
97
+ output: err.stdout || '',
98
+ error: err.stderr || err.message,
99
+ exitCode: err.code || 1
100
+ }
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Install a hook
106
+ */
107
+ async function installHook(repoDir, hookName, script) {
108
+ if (!HOOK_TYPES.includes(hookName)) {
109
+ throw new Error(`Invalid hook type: ${hookName}`)
110
+ }
111
+
112
+ const hooksDir = getHooksDir(repoDir)
113
+ await fs.mkdir(hooksDir, { recursive: true })
114
+
115
+ const hookPath = path.join(hooksDir, hookName)
116
+
117
+ // Ensure script has shebang
118
+ let finalScript = script
119
+ if (!script.startsWith('#!')) {
120
+ finalScript = '#!/bin/sh\n' + script
121
+ }
122
+
123
+ await fs.writeFile(hookPath, finalScript, { mode: 0o755 })
124
+
125
+ return { installed: true, path: hookPath }
126
+ }
127
+
128
+ /**
129
+ * Remove a hook
130
+ */
131
+ async function removeHook(repoDir, hookName) {
132
+ if (!HOOK_TYPES.includes(hookName)) {
133
+ throw new Error(`Invalid hook type: ${hookName}`)
134
+ }
135
+
136
+ const hookPath = path.join(getHooksDir(repoDir), hookName)
137
+
138
+ try {
139
+ await fs.unlink(hookPath)
140
+ return { removed: true }
141
+ } catch (err) {
142
+ if (err.code === 'ENOENT') {
143
+ return { removed: false, error: 'Hook does not exist' }
144
+ }
145
+ throw err
146
+ }
147
+ }
148
+
149
+ /**
150
+ * ListAll hooks
151
+ */
152
+ async function listHooks(repoDir) {
153
+ const hooksDir = getHooksDir(repoDir)
154
+ const hooks = []
155
+
156
+ try {
157
+ const files = await fs.readdir(hooksDir)
158
+
159
+ for (const file of files) {
160
+ if (HOOK_TYPES.includes(file)) {
161
+ const hookPath = path.join(hooksDir, file)
162
+ const stat = await fs.stat(hookPath)
163
+ const isExecutable = (stat.mode & 0o111) !== 0
164
+
165
+ hooks.push({
166
+ name: file,
167
+ path: hookPath,
168
+ executable: isExecutable,
169
+ size: stat.size
170
+ })
171
+ }
172
+ }
173
+ } catch (err) {
174
+ if (err.code !== 'ENOENT') {
175
+ throw err
176
+ }
177
+ }
178
+
179
+ return hooks
180
+ }
181
+
182
+ /**
183
+ * Read hook content
184
+ */
185
+ async function readHook(repoDir, hookName) {
186
+ if (!HOOK_TYPES.includes(hookName)) {
187
+ throw new Error(`Invalid hook type: ${hookName}`)
188
+ }
189
+
190
+ const hookPath = path.join(getHooksDir(repoDir), hookName)
191
+
192
+ try {
193
+ const content = await fs.readFile(hookPath, 'utf8')
194
+ return { content, path: hookPath }
195
+ } catch (err) {
196
+ if (err.code === 'ENOENT') {
197
+ return { content: null, error: 'Hook does not exist' }
198
+ }
199
+ throw err
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Sample hooks for common use cases
205
+ */
206
+ const SAMPLE_HOOKS = {
207
+ 'pre-commit': `#!/bin/sh
208
+ # Pre-commit hook: Run linting before commit
209
+ echo "Running pre-commit checks..."
210
+
211
+ # Example: Run linter
212
+ # npm run lint
213
+ # if [ $? -ne 0 ]; then
214
+ # echo "Linting failed. Commit aborted."
215
+ # exit 1
216
+ # fi
217
+
218
+ echo "Pre-commit checks passed!"
219
+ exit 0
220
+ `,
221
+ 'post-commit': `#!/bin/sh
222
+ # Post-commit hook: Log commit info
223
+ echo "Commit completed: $(git log -1 --pretty=%B)"
224
+ exit 0
225
+ `,
226
+ 'pre-push': `#!/bin/sh
227
+ # Pre-push hook: Run tests before push
228
+ echo "Running tests before push..."
229
+
230
+ # Example: Run tests
231
+ # npm test
232
+ # if [ $? -ne 0 ]; then
233
+ # echo "Tests failed. Push aborted."
234
+ # exit 1
235
+ # fi
236
+
237
+ echo "Tests passed!"
238
+ exit 0
239
+ `
240
+ }
241
+
242
+ module.exports = {
243
+ HOOK_TYPES,
244
+ hookExists,
245
+ executeHook,
246
+ installHook,
247
+ removeHook,
248
+ listHooks,
249
+ readHook,
250
+ SAMPLE_HOOKS
251
+ }