Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

399 wiersze
19 KiB

8 lat temu
  1. 'use strict';
  2. import { Functions, Iterables, Strings } from './system';
  3. import { CancellationToken, CodeLens, CodeLensProvider, commands, DocumentSelector, Event, EventEmitter, ExtensionContext, Position, Range, SymbolInformation, SymbolKind, TextDocument, Uri, workspace } from 'vscode';
  4. import { Commands } from './commands';
  5. import { BuiltInCommands, DocumentSchemes } from './constants';
  6. import { CodeLensCommand, CodeLensLocation, IConfig, ICodeLensLanguageLocation } from './configuration';
  7. import { GitCommit, GitService, GitUri, IGitBlame, IGitBlameLines } from './gitService';
  8. import { Logger } from './logger';
  9. import * as moment from 'moment';
  10. export class GitRecentChangeCodeLens extends CodeLens {
  11. constructor(private blame: () => IGitBlameLines, public uri: GitUri, public symbolKind: SymbolKind, public blameRange: Range, public isFullRange: boolean, range: Range) {
  12. super(range);
  13. }
  14. getBlame(): IGitBlameLines {
  15. return this.blame();
  16. }
  17. }
  18. export class GitAuthorsCodeLens extends CodeLens {
  19. constructor(private blame: () => IGitBlameLines, public uri: GitUri, public symbolKind: SymbolKind, public blameRange: Range, public isFullRange: boolean, range: Range) {
  20. super(range);
  21. }
  22. getBlame(): IGitBlameLines {
  23. return this.blame();
  24. }
  25. }
  26. export class GitCodeLensProvider implements CodeLensProvider {
  27. private _onDidChangeCodeLensesEmitter = new EventEmitter<void>();
  28. public get onDidChangeCodeLenses(): Event<void> {
  29. return this._onDidChangeCodeLensesEmitter.event;
  30. }
  31. static selector: DocumentSelector = { scheme: DocumentSchemes.File };
  32. private _config: IConfig;
  33. private _documentIsDirty: boolean;
  34. constructor(context: ExtensionContext, private git: GitService) {
  35. this._config = workspace.getConfiguration('').get<IConfig>('gitlens');
  36. }
  37. reset() {
  38. this._config = workspace.getConfiguration('').get<IConfig>('gitlens');
  39. Logger.log('Triggering a reset of the git CodeLens provider');
  40. this._onDidChangeCodeLensesEmitter.fire();
  41. }
  42. async provideCodeLenses(document: TextDocument, token: CancellationToken): Promise<CodeLens[]> {
  43. this._documentIsDirty = document.isDirty;
  44. let languageLocations = this._config.codeLens.languageLocations.find(_ => _.language.toLowerCase() === document.languageId);
  45. if (languageLocations == null) {
  46. languageLocations = {
  47. language: undefined,
  48. location: this._config.codeLens.location,
  49. customSymbols: this._config.codeLens.locationCustomSymbols
  50. } as ICodeLensLanguageLocation;
  51. }
  52. const lenses: CodeLens[] = [];
  53. if (languageLocations.location === CodeLensLocation.None) return lenses;
  54. const gitUri = await GitUri.fromUri(document.uri, this.git);
  55. const blamePromise = this.git.getBlameForFile(gitUri);
  56. let blame: IGitBlame;
  57. if (languageLocations.location === CodeLensLocation.Document) {
  58. blame = await blamePromise;
  59. if (!blame || !blame.lines.length) return lenses;
  60. }
  61. else {
  62. const values = await Promise.all([
  63. blamePromise as Promise<any>,
  64. commands.executeCommand(BuiltInCommands.ExecuteDocumentSymbolProvider, document.uri) as Promise<any>
  65. ]);
  66. blame = values[0] as IGitBlame;
  67. if (!blame || !blame.lines.length) return lenses;
  68. const symbols = values[1] as SymbolInformation[];
  69. Logger.log('GitCodeLensProvider.provideCodeLenses:', `${symbols.length} symbol(s) found`);
  70. symbols.forEach(sym => this._provideCodeLens(gitUri, document, sym, languageLocations, blame, lenses));
  71. }
  72. if (languageLocations.location !== CodeLensLocation.Custom || (languageLocations.customSymbols || []).find(_ => _.toLowerCase() === 'file')) {
  73. // Check if we have a lens for the whole document -- if not add one
  74. if (!lenses.find(l => l.range.start.line === 0 && l.range.end.line === 0)) {
  75. const blameRange = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
  76. let blameForRangeFn: () => IGitBlameLines;
  77. if (this._documentIsDirty || this._config.codeLens.recentChange.enabled) {
  78. blameForRangeFn = Functions.once(() => this.git.getBlameForRangeSync(blame, gitUri, blameRange));
  79. lenses.push(new GitRecentChangeCodeLens(blameForRangeFn, gitUri, SymbolKind.File, blameRange, true, new Range(0, 0, 0, blameRange.start.character)));
  80. }
  81. if (this._config.codeLens.authors.enabled) {
  82. if (!blameForRangeFn) {
  83. blameForRangeFn = Functions.once(() => this.git.getBlameForRangeSync(blame, gitUri, blameRange));
  84. }
  85. if (!this._documentIsDirty) {
  86. lenses.push(new GitAuthorsCodeLens(blameForRangeFn, gitUri, SymbolKind.File, blameRange, true, new Range(0, 1, 0, blameRange.start.character)));
  87. }
  88. }
  89. }
  90. }
  91. return lenses;
  92. }
  93. private _validateSymbolAndGetBlameRange(document: TextDocument, symbol: SymbolInformation, languageLocation: ICodeLensLanguageLocation): Range | undefined {
  94. let valid: boolean = false;
  95. let range: Range | undefined;
  96. switch (languageLocation.location) {
  97. case CodeLensLocation.All:
  98. case CodeLensLocation.DocumentAndContainers:
  99. switch (symbol.kind) {
  100. case SymbolKind.File:
  101. valid = true;
  102. // Adjust the range to be the whole file
  103. range = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
  104. break;
  105. case SymbolKind.Package:
  106. case SymbolKind.Module:
  107. // Adjust the range to be the whole file
  108. if (symbol.location.range.start.line === 0 && symbol.location.range.end.line === 0) {
  109. range = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
  110. }
  111. valid = true;
  112. break;
  113. case SymbolKind.Namespace:
  114. case SymbolKind.Class:
  115. case SymbolKind.Interface:
  116. valid = true;
  117. break;
  118. case SymbolKind.Constructor:
  119. case SymbolKind.Method:
  120. case SymbolKind.Function:
  121. case SymbolKind.Property:
  122. case SymbolKind.Enum:
  123. valid = languageLocation.location === CodeLensLocation.All;
  124. break;
  125. }
  126. break;
  127. case CodeLensLocation.Custom:
  128. valid = !!(languageLocation.customSymbols || []).find(_ => _.toLowerCase() === SymbolKind[symbol.kind].toLowerCase());
  129. if (valid) {
  130. switch (symbol.kind) {
  131. case SymbolKind.File:
  132. // Adjust the range to be the whole file
  133. range = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
  134. break;
  135. case SymbolKind.Package:
  136. case SymbolKind.Module:
  137. // Adjust the range to be the whole file
  138. if (symbol.location.range.start.line === 0 && symbol.location.range.end.line === 0) {
  139. range = document.validateRange(new Range(0, 1000000, 1000000, 1000000));
  140. }
  141. break;
  142. }
  143. }
  144. break;
  145. }
  146. return valid ? range || symbol.location.range : undefined;
  147. }
  148. private _provideCodeLens(gitUri: GitUri, document: TextDocument, symbol: SymbolInformation, languageLocation: ICodeLensLanguageLocation, blame: IGitBlame, lenses: CodeLens[]): void {
  149. const blameRange = this._validateSymbolAndGetBlameRange(document, symbol, languageLocation);
  150. if (!blameRange) return;
  151. const line = document.lineAt(symbol.location.range.start);
  152. // Make sure there is only 1 lens per line
  153. if (lenses.length && lenses[lenses.length - 1].range.start.line === line.lineNumber) return;
  154. let startChar = -1;
  155. try {
  156. startChar = line.text.search(`\\b${Strings.escapeRegExp(symbol.name)}\\b`);
  157. }
  158. catch (ex) { }
  159. if (startChar === -1) {
  160. startChar = line.firstNonWhitespaceCharacterIndex;
  161. }
  162. else {
  163. startChar += Math.floor(symbol.name.length / 2);
  164. }
  165. let blameForRangeFn: () => IGitBlameLines;
  166. if (this._documentIsDirty || this._config.codeLens.recentChange.enabled) {
  167. blameForRangeFn = Functions.once(() => this.git.getBlameForRangeSync(blame, gitUri, blameRange));
  168. lenses.push(new GitRecentChangeCodeLens(blameForRangeFn, gitUri, symbol.kind, blameRange, false, line.range.with(new Position(line.range.start.line, startChar))));
  169. startChar++;
  170. }
  171. if (this._config.codeLens.authors.enabled) {
  172. let multiline = !blameRange.isSingleLine;
  173. // HACK for Omnisharp, since it doesn't return full ranges
  174. if (!multiline && document.languageId === 'csharp') {
  175. switch (symbol.kind) {
  176. case SymbolKind.File:
  177. break;
  178. case SymbolKind.Package:
  179. case SymbolKind.Module:
  180. case SymbolKind.Namespace:
  181. case SymbolKind.Class:
  182. case SymbolKind.Interface:
  183. case SymbolKind.Constructor:
  184. case SymbolKind.Method:
  185. case SymbolKind.Function:
  186. case SymbolKind.Enum:
  187. multiline = true;
  188. break;
  189. }
  190. }
  191. if (multiline) {
  192. if (!blameForRangeFn) {
  193. blameForRangeFn = Functions.once(() => this.git.getBlameForRangeSync(blame, gitUri, blameRange));
  194. }
  195. if (!this._documentIsDirty) {
  196. lenses.push(new GitAuthorsCodeLens(blameForRangeFn, gitUri, symbol.kind, blameRange, false, line.range.with(new Position(line.range.start.line, startChar))));
  197. }
  198. }
  199. }
  200. }
  201. resolveCodeLens(lens: CodeLens, token: CancellationToken): CodeLens | Thenable<CodeLens> {
  202. if (lens instanceof GitRecentChangeCodeLens) return this._resolveGitRecentChangeCodeLens(lens, token);
  203. if (lens instanceof GitAuthorsCodeLens) return this._resolveGitAuthorsCodeLens(lens, token);
  204. return Promise.reject<CodeLens>(undefined);
  205. }
  206. _resolveGitRecentChangeCodeLens(lens: GitRecentChangeCodeLens, token: CancellationToken): CodeLens {
  207. // Since blame information isn't valid when there are unsaved changes -- update the lenses appropriately
  208. let title: string;
  209. if (this._documentIsDirty) {
  210. if (this._config.codeLens.recentChange.enabled && this._config.codeLens.authors.enabled) {
  211. title = 'Cannot determine recent change or authors (unsaved changes)';
  212. }
  213. else if (this._config.codeLens.recentChange.enabled) {
  214. title = 'Cannot determine recent change (unsaved changes)';
  215. }
  216. else {
  217. title = 'Cannot determine authors (unsaved changes)';
  218. }
  219. lens.command = {
  220. title: title,
  221. command: undefined
  222. };
  223. return lens;
  224. }
  225. const blame = lens.getBlame();
  226. const recentCommit = Iterables.first(blame.commits.values());
  227. title = `${recentCommit.author}, ${moment(recentCommit.date).fromNow()}`;
  228. if (this._config.advanced.codeLens.debug) {
  229. title += ` [${SymbolKind[lens.symbolKind]}(${lens.blameRange.start.line + 1}-${lens.blameRange.end.line + 1}), Commit (${recentCommit.shortSha})]`;
  230. }
  231. switch (this._config.codeLens.recentChange.command) {
  232. case CodeLensCommand.BlameAnnotate: return this._applyBlameAnnotateCommand<GitRecentChangeCodeLens>(title, lens, blame);
  233. case CodeLensCommand.ShowBlameHistory: return this._applyShowBlameHistoryCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  234. case CodeLensCommand.ShowFileHistory: return this._applyShowFileHistoryCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  235. case CodeLensCommand.DiffWithPrevious: return this._applyDiffWithPreviousCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  236. case CodeLensCommand.ShowQuickCommitDetails: return this._applyShowQuickCommitDetailsCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  237. case CodeLensCommand.ShowQuickCommitFileDetails: return this._applyShowQuickCommitFileDetailsCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  238. case CodeLensCommand.ShowQuickFileHistory: return this._applyShowQuickFileHistoryCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  239. case CodeLensCommand.ShowQuickCurrentBranchHistory: return this._applyShowQuickBranchHistoryCommand<GitRecentChangeCodeLens>(title, lens, blame, recentCommit);
  240. default: return lens;
  241. }
  242. }
  243. _resolveGitAuthorsCodeLens(lens: GitAuthorsCodeLens, token: CancellationToken): CodeLens {
  244. const blame = lens.getBlame();
  245. const count = blame.authors.size;
  246. let title = `${count} ${count > 1 ? 'authors' : 'author'} (${Iterables.first(blame.authors.values()).name}${count > 1 ? ' and others' : ''})`;
  247. if (this._config.advanced.codeLens.debug) {
  248. title += ` [${SymbolKind[lens.symbolKind]}(${lens.blameRange.start.line + 1}-${lens.blameRange.end.line + 1}), Authors (${Iterables.join(Iterables.map(blame.authors.values(), _ => _.name), ', ')})]`;
  249. }
  250. switch (this._config.codeLens.authors.command) {
  251. case CodeLensCommand.BlameAnnotate: return this._applyBlameAnnotateCommand<GitAuthorsCodeLens>(title, lens, blame);
  252. case CodeLensCommand.ShowBlameHistory: return this._applyShowBlameHistoryCommand<GitAuthorsCodeLens>(title, lens, blame);
  253. case CodeLensCommand.ShowFileHistory: return this._applyShowFileHistoryCommand<GitAuthorsCodeLens>(title, lens, blame);
  254. case CodeLensCommand.DiffWithPrevious: return this._applyDiffWithPreviousCommand<GitAuthorsCodeLens>(title, lens, blame);
  255. case CodeLensCommand.ShowQuickCommitDetails: return this._applyShowQuickCommitDetailsCommand<GitAuthorsCodeLens>(title, lens, blame);
  256. case CodeLensCommand.ShowQuickCommitFileDetails: return this._applyShowQuickCommitFileDetailsCommand<GitAuthorsCodeLens>(title, lens, blame);
  257. case CodeLensCommand.ShowQuickFileHistory: return this._applyShowQuickFileHistoryCommand<GitAuthorsCodeLens>(title, lens, blame);
  258. case CodeLensCommand.ShowQuickCurrentBranchHistory: return this._applyShowQuickBranchHistoryCommand<GitAuthorsCodeLens>(title, lens, blame);
  259. default: return lens;
  260. }
  261. }
  262. _applyBlameAnnotateCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines): T {
  263. lens.command = {
  264. title: title,
  265. command: Commands.ToggleBlame,
  266. arguments: [Uri.file(lens.uri.fsPath)]
  267. };
  268. return lens;
  269. }
  270. _applyShowBlameHistoryCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  271. let line = lens.range.start.line;
  272. if (commit) {
  273. const blameLine = commit.lines.find(_ => _.line === line);
  274. if (blameLine) {
  275. line = blameLine.originalLine;
  276. }
  277. }
  278. const position = lens.isFullRange ? new Position(1, 0) : lens.range.start;
  279. lens.command = {
  280. title: title,
  281. command: Commands.ShowBlameHistory,
  282. arguments: [Uri.file(lens.uri.fsPath), lens.blameRange, position, commit && commit.sha, line]
  283. };
  284. return lens;
  285. }
  286. _applyShowFileHistoryCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  287. let line = lens.range.start.line;
  288. if (commit) {
  289. const blameLine = commit.lines.find(_ => _.line === line);
  290. if (blameLine) {
  291. line = blameLine.originalLine;
  292. }
  293. }
  294. const position = lens.isFullRange ? new Position(1, 0) : lens.range.start;
  295. lens.command = {
  296. title: title,
  297. command: Commands.ShowFileHistory,
  298. arguments: [Uri.file(lens.uri.fsPath), position, commit && commit.sha, line]
  299. };
  300. return lens;
  301. }
  302. _applyDiffWithPreviousCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  303. if (!commit) {
  304. const blameLine = blame.allLines[lens.range.start.line];
  305. commit = blame.commits.get(blameLine.sha);
  306. }
  307. lens.command = {
  308. title: title,
  309. command: Commands.DiffWithPrevious,
  310. arguments: [
  311. Uri.file(lens.uri.fsPath),
  312. commit,
  313. lens.isFullRange ? undefined : lens.blameRange
  314. ]
  315. };
  316. return lens;
  317. }
  318. _applyShowQuickCommitDetailsCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  319. lens.command = {
  320. title: title,
  321. command: CodeLensCommand.ShowQuickCommitDetails,
  322. arguments: [Uri.file(lens.uri.fsPath), commit.sha, commit]
  323. };
  324. return lens;
  325. }
  326. _applyShowQuickCommitFileDetailsCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  327. lens.command = {
  328. title: title,
  329. command: CodeLensCommand.ShowQuickCommitFileDetails,
  330. arguments: [Uri.file(lens.uri.fsPath), commit.sha, commit]
  331. };
  332. return lens;
  333. }
  334. _applyShowQuickFileHistoryCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  335. lens.command = {
  336. title: title,
  337. command: CodeLensCommand.ShowQuickFileHistory,
  338. arguments: [Uri.file(lens.uri.fsPath), lens.isFullRange ? undefined : lens.blameRange]
  339. };
  340. return lens;
  341. }
  342. _applyShowQuickBranchHistoryCommand<T extends GitRecentChangeCodeLens | GitAuthorsCodeLens>(title: string, lens: T, blame: IGitBlameLines, commit?: GitCommit): T {
  343. lens.command = {
  344. title: title,
  345. command: CodeLensCommand.ShowQuickCurrentBranchHistory,
  346. arguments: [Uri.file(lens.uri.fsPath)]
  347. };
  348. return lens;
  349. }
  350. }