-
Notifications
You must be signed in to change notification settings - Fork 5
/
hg-utils.coffee
478 lines (390 loc) · 12.8 KB
/
hg-utils.coffee
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
fs = require 'fs'
path = require 'path'
util = require 'util'
urlParser = require 'url'
{spawnSync} = require 'child_process'
diffLib = require 'jsdifflib'
###
Section: Constants used for file/buffer checking against changes
###
statusIndexNew = 1 << 0
statusIndexDeleted = 1 << 2
statusWorkingDirNew = 1 << 7
statusWorkingDirModified = 1 << 8
statusWorkingDirDelete = 1 << 9
statusWorkingDirTypeChange = 1 << 10
statusIgnored = 1 << 14
modifiedStatusFlags = statusWorkingDirModified | statusWorkingDirDelete |
statusWorkingDirTypeChange | statusIndexDeleted
newStatusFlags = statusWorkingDirNew | statusIndexNew
deletedStatusFlags = statusWorkingDirDelete | statusIndexDeleted
suppressHgWarnings = [
'W200005' # hg: warning: W200005: 'file' is not under version control
'E200009' # Could not cat all targets because some targets are not versioned
]
class Repository
username: null
password: null
rootPath: null
isHgRepository: false
binaryAvailable: false
version: null
url: null
urlPath: null
shortHead: null
revision: null
###
Section: Initialization and startup checks
###
constructor: (repoRootPath) ->
@rootPath = path.normalize(repoRootPath)
# Checks if there is a hg binary in the os searchpath and returns the
# binary version string.
#
# Returns a {boolean}
checkBinaryAvailable: () ->
@version = @getHgVersion()
if @version?
@binaryAvailable = true
else
@binaryAvailable = false
return @binaryAvailable
# Parses info from `hg info` and `hgversion` command and checks if repo infos have changed
# since last check
#
# Returns a {boolean} if repo infos have changed
checkRepositoryHasChanged: () ->
hasChanged = false
revision = @getHgWorkingCopyRevision()
if revision?
if revision != @revision
@revision = revision
hasChanged = true
# info = @getHgInfo()
# if info? && info.url?
# if info.url != @url
# @url = info.url
# urlParts = urlParser.parse(info.url)
# @urlPath = urlParts.path
# pathParts = @urlPath.split('/')
# @shortHead = if pathParts.length > 0 then pathParts.pop() else ''
# hasChanged = true
return hasChanged
getShortHead: () ->
branchFile = @rootPath + '/.hg/branch'
if !fs.existsSync(branchFile)
return 'default'
return fs.readFileSync branchFile, 'utf8'
###
Section: TreeView Path Mercurial status
###
# Parses `hg status`. Gets initially called by hg-repository.refreshStatus()
#
# Returns a {Array} array keys are paths, values are change constants. Or null
getStatus: () ->
statuses = @getHgStatus()
return statuses
# Parses `hg status`. Gets called by hg-repository.refreshStatus()
#
# Returns an {Array} Array keys are paths, values are change constants
getPathStatus: (hgPath) ->
status = @getHgPathStatus(hgPath)
return status
getPath: () ->
return @rootPath
isStatusModified: (status=0) ->
(status & modifiedStatusFlags) > 0
isPathModified: (path) ->
@isStatusModified(@getPathStatus(path))
isStatusNew: (status=0) ->
(status & newStatusFlags) > 0
isPathNew: (path) ->
@isStatusNew(@getPathStatus(path))
isStatusDeleted: (status=0) ->
(status & deletedStatusFlags) > 0
isPathDeleted: (path) ->
@isStatusDeleted(@getPathStatus(path))
isPathStaged: (path) ->
@isStatusStaged(@getPathStatus(path))
isStatusIgnored: (status=0) ->
(status & statusIgnored) > 0
isStatusStaged: (status=0) ->
(status & indexStatusFlags) > 0
###
Section: Editor Mercurial line diffs
###
# Public: Retrieves the number of lines added and removed to a path.
#
# This compares the working directory contents of the path to the `HEAD`
# version.
#
# * `path` The {String} path to check.
# * `lastRevFileContent` filecontent from latest hg revision.
#
# Returns an {Object} with the following keys:
# * `added` The {Number} of added lines.
# * `deleted` The {Number} of deleted lines.
getDiffStats: (path, lastRevFileContent) ->
diffStats = {
added: 0
deleted: 0
}
if (lastRevFileContent? && fs.existsSync(path))
base = diffLib.stringAsLines(lastRevFileContent)
newtxt = diffLib.stringAsLines(fs.readFileSync(path).toString())
# create a SequenceMatcher instance that diffs the two sets of lines
sm = new diffLib.SequenceMatcher(base, newtxt)
# get the opcodes from the SequenceMatcher instance
# opcodes is a list of 3-tuples describing what changes should be made to the base text
# in order to yield the new text
opcodes = sm.get_opcodes()
for opcode in opcodes
if opcode[0] == 'insert' || opcode[0] == 'replace'
diffStats.added += (opcode[2] - opcode[1]) + (opcode[4] - opcode[3])
if opcode[0] == 'delete'
diffStats.deleted += (opcode[2] - opcode[1]) - (opcode[4] - opcode[3])
return diffStats
# Public: Retrieves the line diffs comparing the `HEAD` version of the given
# path and the given text.
#
# * `lastRevFileContent` filecontent from latest hg revision.
# * `text` The {String} to compare against the `HEAD` contents
#
# Returns an {Array} of hunk {Object}s with the following keys:
# * `oldStart` The line {Number} of the old hunk.
# * `newStart` The line {Number} of the new hunk.
# * `oldLines` The {Number} of lines in the old hunk.
# * `newLines` The {Number} of lines in the new hunk
getLineDiffs: (lastRevFileContent, text, options) ->
hunks = []
if (lastRevFileContent?)
base = diffLib.stringAsLines(lastRevFileContent)
newtxt = diffLib.stringAsLines(text)
# create a SequenceMatcher instance that diffs the two sets of lines
sm = new diffLib.SequenceMatcher(base, newtxt)
# get the opcodes from the SequenceMatcher instance
# opcodes is a list of 3-tuples describing what changes should be made to the base text
# in order to yield the new text
opcodes = sm.get_opcodes()
actions = ['replace', 'insert', 'delete']
for opcode in opcodes
if actions.indexOf(opcode[0]) >= 0
hunk = {
oldStart: opcode[1] + 1
oldLines: opcode[2] - opcode[1]
newStart: opcode[3] + 1
newLines: opcode[4] - opcode[3]
}
if opcode[0] == 'delete'
hunk.newStart = hunk.newStart - 1
hunks.push(hunk)
return hunks
###
Section: Mercurial Command handling
###
# Spawns an hg command and returns stdout or throws an error if process
# exits with an exitcode unequal to zero.
#
# * `params` The {Array} for commandline arguments
#
# Returns a {String} of process stdout
hgCommand: (params) ->
if !params
params = []
if !util.isArray(params)
params = [params]
return '' unless @isCommandForRepo(params)
child = spawnSync('hg', params)
if child.status != 0
if child.stderr
throw new Error(child.stderr.toString())
if child.stdout
throw new Error(child.stdout.toString())
throw new Error('Error trying to execute Mercurial binary with params \'' + params + '\'')
return child.stdout.toString()
handleHgError: (error) ->
logMessage = true
message = error.message
for suppressHgWarning in suppressHgWarnings
if message.indexOf(suppressHgWarning) > 0
logMessage = false
break
if logMessage
console.error('Mercurial', 'hg-utils', error)
# Returns on success the version from the hg binary. Otherwise null.
#
# Returns a {String} containing the hg-binary version
getHgVersion: () ->
try
version = @hgCommand(['--version', '--quiet'])
return version.trim()
catch error
@handleHgError(error)
return null
# Returns on success the current working copy revision. Otherwise null.
#
# Returns a {String} with the current working copy revision
getHgWorkingCopyRevision: () ->
try
return @hgCommand(['id', '-i', @rootPath])
catch error
@handleHgError(error)
return null
# Returns on success an hg-ignores array. Otherwise null.
# Array keys are paths, values {Number} representing the status
#
# Returns a {Array} with path and statusnumber
getRecursiveIgnoreStatuses: () ->
try
files = @hgCommand(['status', @rootPath])
catch error
@handleHgError(error)
return []
items = []
entries = files.split('\n')
if entries
for entry in entries
parts = entry.split(' ')
status = parts[0]
pathPart = parts[1]
if pathPart? && status?
if (status is 'I') # || status is '?')
items.push(pathPart.replace('..', ''))
return items
# Returns on success an hg-status array. Otherwise null.
# Array keys are paths, values {Number} representing the status
#
# Returns a {Array} with path and statusnumber
getHgStatus: () ->
try
files = @hgCommand(['status', @rootPath])
catch error
@handleHgError(error)
return null
items = []
entries = files.split('\n')
if entries
for entry in entries
parts = entry.split(' ')
status = parts[0]
pathPart = parts[1]
if pathPart? && status?
items.push({
'path': pathPart
'status': @mapHgStatus(status)
})
return items
# Returns on success a status bitmask. Otherwise null.
#
# * `hgPath` The path {String} for the status inquiry
#
# Returns a {Number} representing the status
getHgPathStatus: (hgPath) ->
return null unless hgPath
try
files = @hgCommand(['status', hgPath])
catch error
@handleHgError(error)
return null
items = []
entries = files.split('\n')
if entries
path_status = 0
for entry in entries
parts = entry.split(' ')
status = parts[0]
pathPart = parts[1]
if status?
path_status |= @mapHgStatus(status)
return path_status
else
return null
# Translates the status {String} from `hg status` command into a
# status {Number}.
#
# * `status` The status {String} from `hg status` command
#
# Returns a {Number} representing the status
mapHgStatus: (status) ->
return 0 unless status
statusBitmask = 0
# status workingdir
if status == 'M'
statusBitmask = statusWorkingDirModified
if status == '?'
statusBitmask = statusWorkingDirNew
if status == '!'
statusBitmask = statusWorkingDirDelete
if status == 'I'
statusBitmask = statusIgnored
if status == 'M'
statusBitmask = statusWorkingDirTypeChange
# status index
if status == 'A'
statusBitmask = statusIndexNew
if status == 'R'
statusBitmask = statusIndexDeleted
return statusBitmask
# This retrieves the contents of the hgpath from the `HEAD` on success.
# Otherwise null.
#
# * `hgPath` The path {String}
#
# Returns the {String} as filecontent
getHgCat: (hgPath) ->
params = ['cat', hgPath]
try
fileContent = @hgCommand(params)
return fileContent
catch error
if /no such file in rev/.test(error)
return null
@handleHgError(error)
return null
# This checks to see if the current params indicate whether we are working
# with the current repository.
#
# * `params` The params that are going to be sent to the hg command {Array}
#
# Returns a {Boolean} indicating if the rootPath was found in the params
isCommandForRepo: (params) ->
rootPath = @rootPath
paths = params.filter (param) ->
normalizedPath = path.normalize((param || ''))
return normalizedPath.startsWith(rootPath)
return paths.length > 0
exports.isStatusModified = (status) ->
return (status & modifiedStatusFlags) > 0
exports.isStatusNew = (status) ->
return (status & newStatusFlags) > 0
exports.isStatusDeleted = (status) ->
return (status & deletedStatusFlags) > 0
exports.isStatusIgnored = (status) ->
return (status & statusIgnored) > 0
exports.isStatusStaged = (status) ->
return (status & indexStatusFlags) > 0
# creates and returns a new {Repository} object if hg-binary could be found
# and several infos from are successfully read. Otherwise null.
#
# * `repositoryPath` The path {String} to the repository root directory
#
# Returns a new {Repository} object
openRepository = (repositoryPath) ->
repository = new Repository(repositoryPath)
if repository.checkBinaryAvailable()
return repository
else
return null
exports.open = (repositoryPath) ->
return openRepository(repositoryPath)
openRepositoryAsync = (repositoryPath) ->
return new Promise((resolve, reject) ->
repository = new Repository(repositoryPath)
if repository.checkBinaryAvailable()
resolve(repository)
else
reject(null)
)
exports.openAsync = (repositoryPath) ->
return openRepositoryAsync(repositoryPath).then((repo) ->
return repo)