Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix gitlab gitkeep issue #3199

Merged
merged 15 commits into from
Jan 16, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/friendly-geese-tell.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@tokens-studio/figma-plugin": patch
---

Fix issue of lingering gitkeep files in non-empty gitlab directories
78 changes: 52 additions & 26 deletions packages/tokens-studio-for-figma/src/storage/GitlabTokenStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,45 @@ export class GitlabTokenStorage extends GitTokenStorage {
return false;
}

private async cleanupGitkeepFiles(path: string, branch: string, message: string) {
const trees = await this.gitlabClient.Repositories.allRepositoryTrees(this.projectId!, {
path,
ref: branch,
recursive: true,
});

const gitkeepDeletions: CommitAction[] = [];
const directories = trees.reduce((acc: Record<string, string[]>, file) => {
const dir = file.path.substring(0, file.path.lastIndexOf('/'));
if (!acc[dir]) acc[dir] = [];
acc[dir].push(file.path);
return acc;
}, {});

for (const [dir, files] of Object.entries(directories)) {
const hasGitkeep = files.some((file) => file.endsWith('.gitkeep'));
const hasOtherFiles = files.some((file) => !file.endsWith('.gitkeep'));

if (hasGitkeep && hasOtherFiles) {
const gitkeepPath = `${dir}/.gitkeep`;
gitkeepDeletions.push({ action: 'delete', filePath: gitkeepPath });
}
}

if (gitkeepDeletions.length > 0) {
try {
await this.gitlabClient.Commits.create(
this.projectId!,
branch,
message,
gitkeepDeletions,
);
} catch (e) {
console.error('Failed to delete .gitkeep files:', e);
}
}
}

public async read(): Promise<RemoteTokenStorageFile[] | RemoteTokenstorageErrorMessage> {
if (!this.projectId) throw new Error('Missing Project ID');

Expand Down Expand Up @@ -198,7 +237,6 @@ export class GitlabTokenStorage extends GitTokenStorage {
errorMessage: ErrorMessages.VALIDATION_ERROR,
};
} catch (err) {
// Raise error (usually this is an auth error)
console.error(err);
}
return [];
Expand All @@ -208,20 +246,18 @@ export class GitlabTokenStorage extends GitTokenStorage {
if (!this.projectId) throw new Error('Missing Project ID');

const branches = await this.fetchBranches();
const rootPath = this.path.endsWith('.json') ? this.path.split('/').slice(0, -1).join('/') : this.path;
const pathToCreate = this.path.endsWith('.json') ? this.path : `${this.path}/.gitkeep`;

const rootPath = this.path.endsWith('.json')
? this.path.split('/').slice(0, -1).join('/')
: this.path;
if (shouldCreateBranch && !branches.includes(branch)) {
const sourceBranch = this.previousSourceBranch || this.source;
await this.createBranch(branch, sourceBranch);
}

// Directories cannot be created empty (Source: https://gitlab.com/gitlab-org/gitlab/-/issues/247503)
const pathToCreate = this.path.endsWith('.json') ? this.path : `${this.path}/.gitkeep`;
try {
await this.gitlabClient.RepositoryFiles.show(this.projectId, pathToCreate, branch);
} catch (e) {
} catch {
await this.gitlabClient.RepositoryFiles.create(
this.projectId,
pathToCreate,
Expand All @@ -236,40 +272,30 @@ export class GitlabTokenStorage extends GitTokenStorage {
ref: branch,
recursive: true,
});
const jsonFiles = tree.filter((file) => (
file.path.endsWith('.json')
)).sort((a, b) => (
(a.path && b.path) ? a.path.localeCompare(b.path) : 0
)).map((jsonFile) => jsonFile.path);

let gitlabActions: CommitAction[] = Object.entries(changeset).map(([filePath, content]) => ({
action: jsonFiles.includes(filePath) ? 'update' : 'create',
filePath,
content,
}));

if (!this.path.endsWith('.json')) {
const filesToDelete = jsonFiles.filter((jsonFile) => !Object.keys(changeset).some((item) => item.endsWith(jsonFile)));
gitlabActions = gitlabActions.concat(filesToDelete.map((filePath) => ({
action: 'delete',
filePath,
})));
}
const gitlabActions: CommitAction[] = Object.entries(changeset).map(([filePath, content]) => {
const action = tree.some((file) => file.path === filePath) ? 'update' : 'create';
return { action, filePath, content };
});

try {
const response = await this.gitlabClient.Commits.create(
await this.gitlabClient.Commits.create(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

does this have a side-effect? we are kind of returning if it was a successful push, now we are depending on the gitkeep stuff. but if its a single file sync we should never even call the gitkeep action

this.projectId,
branch,
message,
gitlabActions,
);
return !!response;
} catch (e: any) {
if (e.cause.description && String(e.cause.description).includes(ErrorMessages.GITLAB_PUSH_TO_PROTECTED_BRANCH_ERROR)) {
throw new Error(ErrorMessages.GITLAB_PUSH_TO_PROTECTED_BRANCH_ERROR);
}
throw new Error(e);
}

if (!this.path.endsWith('.json')) {
await this.cleanupGitkeepFiles(rootPath, branch, message);
}
return true;
}

public async getLatestCommitDate(): Promise<Date | null> {
Expand Down
Loading