|
| 1 | +import { execSync } from "child_process"; |
| 2 | +import { appendFileSync, writeFileSync } from "fs"; |
| 3 | +import { sep } from "path"; |
| 4 | + |
| 5 | +export default class VersionedFileFixture { |
| 6 | + constructor(private readonly repositoryLocation: string) {} |
| 7 | + |
| 8 | + private name = "example.js"; |
| 9 | + private numberOfLinesInFile = 10; |
| 10 | + private numberOfCommitsForFile = 10; |
| 11 | + private commitDate?: string; |
| 12 | + |
| 13 | + withName(name: string): VersionedFileFixture { |
| 14 | + this.name = name; |
| 15 | + return this; |
| 16 | + } |
| 17 | + |
| 18 | + containing(args: { lines: number }): VersionedFileFixture { |
| 19 | + this.numberOfLinesInFile = args.lines; |
| 20 | + return this; |
| 21 | + } |
| 22 | + |
| 23 | + committed(args: { times: number; date?: string }): VersionedFileFixture { |
| 24 | + this.numberOfCommitsForFile = args.times; |
| 25 | + this.commitDate = args.date; |
| 26 | + return this; |
| 27 | + } |
| 28 | + |
| 29 | + writeOnDisk(): void { |
| 30 | + for (let i = 0; i < this.numberOfCommitsForFile; i++) { |
| 31 | + if (i === 0) { |
| 32 | + this.createFileWithContentInRepository(this.name); |
| 33 | + this.addFileToRepository(); |
| 34 | + } else { |
| 35 | + this.modifyFileWithoutChangingItsLength(i); |
| 36 | + } |
| 37 | + this.commitFile(i); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + private commitFile(i: number): void { |
| 42 | + const commitMessage = `"${this.name}: commit #${i + 1}"`; |
| 43 | + const command = this.commitDate |
| 44 | + ? `GIT_COMMITTER_DATE="${this.commitDate}" git -C ${this.repositoryLocation} commit --all --message=${commitMessage} --date=${this.commitDate}` |
| 45 | + : `git -C ${this.repositoryLocation} commit --all --message=${commitMessage}`; |
| 46 | + try { |
| 47 | + execSync(command); |
| 48 | + } catch (e) { |
| 49 | + console.log(e.stdout.toString()); |
| 50 | + throw e; |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private modifyFileWithoutChangingItsLength(i: number): void { |
| 55 | + appendFileSync( |
| 56 | + `${this.repositoryLocation}${sep}${this.name}`, |
| 57 | + `// change for commit #${i + 1} ` |
| 58 | + ); |
| 59 | + } |
| 60 | + |
| 61 | + private createFileWithContentInRepository(fileName: string): void { |
| 62 | + writeFileSync( |
| 63 | + `${this.repositoryLocation}${sep}${fileName}`, |
| 64 | + new Array(this.numberOfLinesInFile) |
| 65 | + .fill(null) |
| 66 | + .map((value, index) => `console.log(${index});`) |
| 67 | + .join("\n") |
| 68 | + ); |
| 69 | + } |
| 70 | + |
| 71 | + private addFileToRepository(): void { |
| 72 | + execSync(`git -C ${this.repositoryLocation} add --all`); |
| 73 | + } |
| 74 | +} |
0 commit comments