-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathuriGenerator.ts
99 lines (85 loc) · 2.79 KB
/
uriGenerator.ts
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
'use strict'
import * as fs from 'fs'
import * as path from 'path'
import * as tmp from 'tmp'
import { FileStage } from './Git/StashGit'
import GitBridge from './GitBridge'
import StashNode from './StashNode/StashNode'
import { Uri } from 'vscode'
export default class UriGenerator {
public static readonly emptyFileScheme = 'gitdiff-no-contents'
public static readonly fileScheme = 'gitdiff-stashed-contents'
private readonly supportedBinaryFiles = [
'.bmp',
'.gif',
'.jpe',
'.jpg',
'.jpeg',
'.png',
'.webp',
]
private gitBridge: GitBridge
constructor(gitBridge: GitBridge) {
this.gitBridge = gitBridge
tmp.setGracefulCleanup()
}
/**
* Creates a node Uri to be used on Tree items.
*
* @param node the node to be used as base for the URI
*/
public createForTreeItem(node: StashNode): Uri {
return Uri.parse(`${UriGenerator.fileScheme}:${node.path}?type=${node.type}&t=${new Date().getTime()}`)
}
/**
* Creates a node Uri to be used on the diff view.
*
* @param node the node to be used as base for the URI
* @param stage the file stash stage
*/
public async createForDiff(node?: StashNode, stage?: FileStage): Promise<Uri> {
if (!node) {
return Uri.parse(`${UriGenerator.emptyFileScheme}:`)
}
if (this.supportedBinaryFiles.indexOf(path.extname(node.name)) > -1) {
return Uri.file(
this.createTmpFile(
await this.gitBridge.getFileContents(node, stage),
node.name,
).name,
)
}
return this.generateUri(node, stage)
}
/**
* Generates an Uri representing the stash file.
*
* @param node the node to be used as base for the URI
* @param side the editor side
*/
private generateUri(node: StashNode, side?: string): Uri {
const timestamp = new Date().getTime()
const query = `cwd=${node.parent.path}`
+ `&index=${node.parent.index}`
+ `&path=${node.name}`
+ `&oldPath=${node.oldName || ''}`
+ `&type=${node.type}`
+ `&side=${side || ''}`
+ `&t=${timestamp}`
return Uri.parse(`${UriGenerator.fileScheme}:${node.path}?${query}`)
}
/**
* Generates a tmp file with the given content.
*
* @param content the string with the content
* @param filename the string with the filename
*/
private createTmpFile(content: string, filename: string): tmp.FileResult {
const file = tmp.fileSync({
prefix: 'vscode-gitstash-',
postfix: path.extname(filename),
})
fs.writeFileSync(file.name, content)
return file
}
}