OXYGENHUB
# 25103dddd993 oxygen-vscode / src / repository.ts
10.0 KiB · last changed Milestone 0.5: conflict editor CodeLens over oxy markers, keep-this-candidate for tree conflicts, mark resolved, commit resolution label 1 month ago source blame history raw
1
// One Oxygen repository as VS Code sees it: the source control provider,
2
// its resource groups, the status bar item, and the watchers that keep
3
// them fresh (spec §3, §5.1, §5.4).
4
5
import * as vscode from "vscode";
6
import { basename, join, relative } from "node:path";
7
import { BookmarkInfo, Oxy, PathStatus, StatusInfo } from "./oxy";
8
import { baseUri } from "./contentProvider";
9
10
const STATUS_LETTER: Record<PathStatus, string> = {
11
  Added: "A",
12
  Modified: "M",
13
  Removed: "D",
14
  Renamed: "R",
15
  ModeChanged: "X",
16
  ConflictEdited: "‼",
17
  Resolved: "✔",
18
};
19
20
const STATUS_WORD: Record<PathStatus, string> = {
21
  Added: "added",
22
  Modified: "modified",
23
  Removed: "removed",
24
  Renamed: "renamed",
25
  ModeChanged: "mode changed",
26
  ConflictEdited: "conflict markers remain",
27
  Resolved: "conflict resolved",
28
};
29
30
const STATUS_COLOR: Record<PathStatus, string> = {
31
  Added: "gitDecoration.addedResourceForeground",
32
  Modified: "gitDecoration.modifiedResourceForeground",
33
  Removed: "gitDecoration.deletedResourceForeground",
34
  Renamed: "gitDecoration.renamedResourceForeground",
35
  ModeChanged: "gitDecoration.modifiedResourceForeground",
36
  ConflictEdited: "gitDecoration.conflictingResourceForeground",
37
  Resolved: "gitDecoration.stageModifiedResourceForeground",
38
};
39
40
export class OxyResourceState implements vscode.SourceControlResourceState {
41
  readonly resourceUri: vscode.Uri;
42
  readonly decorations: vscode.SourceControlResourceDecorations;
43
  readonly command: vscode.Command;
44
45
  constructor(
46
    readonly repository: Repository,
47
    readonly path: string,
48
    readonly status: PathStatus,
49
  ) {
50
    this.resourceUri = vscode.Uri.file(join(repository.root, path));
51
    this.decorations = {
52
      strikeThrough: status === "Removed",
53
      tooltip: STATUS_WORD[status],
54
      faded: false,
55
    };
56
    this.command = { command: "oxygen.openChanges", title: "Open Changes", arguments: [this] };
57
    this.contextValue = /\.oxy-conflict-\d+$/.test(path) ? "candidate" : status === "ConflictEdited" ? "markers" : status;
58
  }
59
60
  contextValue: string;
61
62
  get letter(): string {
63
    return STATUS_LETTER[this.status];
64
  }
65
66
  get color(): vscode.ThemeColor {
67
    return new vscode.ThemeColor(STATUS_COLOR[this.status]);
68
  }
69
}
70
71
export class Repository implements vscode.Disposable, vscode.QuickDiffProvider {
72
  readonly sourceControl: vscode.SourceControl;
73
  readonly conflictsGroup: vscode.SourceControlResourceGroup;
74
  readonly changesGroup: vscode.SourceControlResourceGroup;
75
  private readonly statusBar: vscode.StatusBarItem;
76
  private readonly syncBar: vscode.StatusBarItem;
77
  private bookmarksLatest: BookmarkInfo[] = [];
78
  private readonly disposables: vscode.Disposable[] = [];
79
  private readonly onDidChangeStatusEmitter = new vscode.EventEmitter<StatusInfo>();
80
  readonly onDidChangeStatus = this.onDidChangeStatusEmitter.event;
81
  private latest: StatusInfo | undefined;
82
  private refreshTimer: NodeJS.Timeout | undefined;
83
  private refreshing: Promise<void> | undefined;
84
  private refreshAgain = false;
85
86
  constructor(
87
    readonly oxy: Oxy,
88
    readonly root: string,
89
    readonly workspaceFolder: vscode.WorkspaceFolder | undefined,
90
  ) {
91
    const rootUri = vscode.Uri.file(root);
92
    this.sourceControl = vscode.scm.createSourceControl("oxygen", `Oxygen (${basename(root)})`, rootUri);
93
    this.sourceControl.quickDiffProvider = this;
94
    this.sourceControl.acceptInputCommand = { command: "oxygen.commit", title: "Commit", arguments: [this] };
95
    this.sourceControl.inputBox.placeholder = "Message (Ctrl+Enter to commit)";
96
    this.conflictsGroup = this.sourceControl.createResourceGroup("conflicts", "Conflicts");
97
    this.conflictsGroup.hideWhenEmpty = true;
98
    this.changesGroup = this.sourceControl.createResourceGroup("changes", "Changes");
99
    this.statusBar = vscode.window.createStatusBarItem("oxygen.status", vscode.StatusBarAlignment.Left, 100);
100
    this.statusBar.name = "Oxygen";
101
    this.statusBar.command = { command: "oxygen.switchBookmark", title: "Switch bookmark", arguments: [this] };
102
    this.syncBar = vscode.window.createStatusBarItem("oxygen.sync", vscode.StatusBarAlignment.Left, 99);
103
    this.syncBar.name = "Oxygen sync";
104
    this.syncBar.command = { command: "oxygen.sync", title: "Sync", arguments: [this] };
105
    this.disposables.push(this.sourceControl, this.conflictsGroup, this.changesGroup, this.statusBar, this.syncBar, this.onDidChangeStatusEmitter);
106
107
    if (vscode.workspace.getConfiguration("oxygen").get<boolean>("autoRefresh", true)) {
108
      // Files in the workspace, except the repository's own store.
109
      const files = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(rootUri, "**/*"));
110
      const onFile = (uri: vscode.Uri) => {
111
        if (!uri.fsPath.startsWith(join(root, ".oxy"))) {
112
          this.scheduleRefresh();
113
        }
114
      };
115
      files.onDidChange(onFile, this, this.disposables);
116
      files.onDidCreate(onFile, this, this.disposables);
117
      files.onDidDelete(onFile, this, this.disposables);
118
      this.disposables.push(files);
119
      // Any operation, including ones run from a terminal, moves the op head.
120
      const ops = vscode.workspace.createFileSystemWatcher(new vscode.RelativePattern(rootUri, ".oxy/ops/head"));
121
      ops.onDidChange(() => this.scheduleRefresh(), this, this.disposables);
122
      ops.onDidCreate(() => this.scheduleRefresh(), this, this.disposables);
123
      this.disposables.push(ops);
124
    }
125
    vscode.window.onDidChangeWindowState((s) => s.focused && this.scheduleRefresh(), this, this.disposables);
126
  }
127
128
  get status(): StatusInfo | undefined {
129
    return this.latest;
130
  }
131
132
  get bookmarks(): BookmarkInfo[] {
133
    return this.bookmarksLatest;
134
  }
135
136
  get currentBookmark(): BookmarkInfo | undefined {
137
    return this.bookmarksLatest.find((b) => b.current);
138
  }
139
140
  /** The repository-relative path of a file under this root, or undefined. */
141
  relativePath(uri: vscode.Uri): string | undefined {
142
    if (uri.scheme !== "file") {
143
      return undefined;
144
    }
145
    const rel = relative(this.root, uri.fsPath);
146
    if (!rel || rel.startsWith("..") || rel.startsWith(".oxy")) {
147
      return undefined;
148
    }
149
    return rel.split("\\").join("/");
150
  }
151
152
  scheduleRefresh(): void {
153
    if (this.refreshTimer) {
154
      clearTimeout(this.refreshTimer);
155
    }
156
    this.refreshTimer = setTimeout(() => void this.refresh(), 250);
157
  }
158
159
  /** Refresh now; a refresh requested during one runs once more afterwards. */
160
  refresh(): Promise<void> {
161
    if (this.refreshing) {
162
      this.refreshAgain = true;
163
      return this.refreshing;
164
    }
165
    this.refreshing = this.doRefresh().finally(() => {
166
      this.refreshing = undefined;
167
      if (this.refreshAgain) {
168
        this.refreshAgain = false;
169
        void this.refresh();
170
      }
171
    });
172
    return this.refreshing;
173
  }
174
175
  private async doRefresh(): Promise<void> {
176
    try {
177
      const [status, prompt, bookmarks] = await Promise.all([this.oxy.status(this.root), this.oxy.prompt(this.root), this.oxy.bookmarks(this.root).catch(() => [] as BookmarkInfo[])]);
178
      this.latest = status;
179
      this.bookmarksLatest = bookmarks;
180
      const conflicted = new Set(status.conflicts.map((c) => c.path).filter((p): p is string => !!p));
181
      const conflicts: OxyResourceState[] = [];
182
      const changes: OxyResourceState[] = [];
183
      for (const p of status.paths) {
184
        const state = new OxyResourceState(this, p.path, p.status);
185
        if (p.status === "ConflictEdited" || p.status === "Resolved" || conflicted.has(p.path)) {
186
          conflicts.push(state);
187
        } else {
188
          changes.push(state);
189
        }
190
      }
191
      // Conflicted files the working copy has not touched yet still need resolving.
192
      for (const c of status.conflicts) {
193
        if (c.path && !status.paths.some((p) => p.path === c.path)) {
194
          conflicts.push(new OxyResourceState(this, c.path, "ConflictEdited"));
195
        }
196
      }
197
      this.conflictsGroup.resourceStates = conflicts;
198
      this.changesGroup.resourceStates = changes;
199
      this.sourceControl.count = status.paths.length + (status.conflicts.length ? status.conflicts.length : 0);
200
      this.updateStatusBar(status, prompt);
201
      this.onDidChangeStatusEmitter.fire(status);
202
    } catch (e) {
203
      this.statusBar.text = "$(warning) oxy";
204
      this.statusBar.tooltip = String(e);
205
      this.statusBar.show();
206
    }
207
  }
208
209
  private updateStatusBar(status: StatusInfo, prompt: string): void {
210
    if (!vscode.workspace.getConfiguration("oxygen").get<boolean>("statusBar.enabled", true)) {
211
      this.statusBar.hide();
212
      return;
213
    }
214
    const text = prompt || `${status.bookmark} ${status.working_copy.slice(0, 8)}`;
215
    this.statusBar.text = text;
216
    this.statusBar.tooltip = new vscode.MarkdownString(
217
      `**Oxygen** ${basename(this.root)}\n\n` +
218
        `Bookmark \`${status.bookmark}\` with ${status.heads} head${status.heads === 1 ? "" : "s"}\n\n` +
219
        (status.conflicted ? `$(warning) The state has conflicts\n\n` : "") +
220
        `${status.paths.length} changed path${status.paths.length === 1 ? "" : "s"}`,
221
      true,
222
    );
223
    this.statusBar.backgroundColor = status.conflicted ? new vscode.ThemeColor("statusBarItem.errorBackground") : undefined;
224
    this.statusBar.show();
225
    const current = this.currentBookmark;
226
    if (current && (current.ahead !== null || current.behind !== null)) {
227
      const ahead = current.ahead ?? 0;
228
      const behind = current.behind ?? 0;
229
      this.syncBar.text = `$(arrow-up)${ahead} $(arrow-down)${behind}`;
230
      this.syncBar.tooltip = `${ahead} change${ahead === 1 ? "" : "s"} to push, ${behind} to pull from origin. Click to sync.`;
231
      this.syncBar.show();
232
    } else {
233
      this.syncBar.hide();
234
    }
235
  }
236
237
  // QuickDiffProvider: the base version of a file, served from oxy.
238
  provideOriginalResource(uri: vscode.Uri): vscode.Uri | undefined {
239
    const rel = this.relativePath(uri);
240
    if (!rel) {
241
      return undefined;
242
    }
243
    const status = this.latest?.paths.find((p) => p.path === rel)?.status;
244
    if (status === "Added") {
245
      return undefined;
246
    }
247
    return baseUri(this.root, rel);
248
  }
249
250
  dispose(): void {
251
    if (this.refreshTimer) {
252
      clearTimeout(this.refreshTimer);
253
    }
254
    for (const d of this.disposables) {
255
      d.dispose();
256
    }
257
  }
258
}