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(3197): Fix sync with Bitbucket #3204

Merged
merged 4 commits into from
Nov 25, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
127 changes: 80 additions & 47 deletions packages/tokens-studio-for-figma/src/storage/BitbucketTokenStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ export class BitbucketTokenStorage extends GitTokenStorage {
Authorization: `Basic ${btoa(`${this.username}:${this.secret}`)}`,
},
cache: 'no-cache',
});
});

if (!response.ok) {
throw new Error(`Failed to read from Bitbucket: ${response.statusText}`);
Expand All @@ -178,14 +178,66 @@ export class BitbucketTokenStorage extends GitTokenStorage {
return allJsonFiles;
}

private async fetchJsonFile(url: string): Promise<GitSingleFileObject> {
const response = await fetch(url, {
headers: {
Authorization: `Basic ${btoa(`${this.username}:${this.secret}`)}`,
},
cache: 'no-cache',
});

if (!response.ok) {
throw new Error(`Failed to read from Bitbucket: ${response.statusText}`);
}

const data = await response.json();

return data;
}

public async read(): Promise<RemoteTokenStorageFile[] | RemoteTokenstorageErrorMessage> {
const normalizedPath = compact(this.path.split('/')).join('/');

try {
const url = `https://api.bitbucket.org/2.0/repositories/${this.owner}/${this.repository}/src/${this.branch}/${normalizedPath}`;
const jsonFiles = await this.fetchJsonFilesFromDirectory(url);

if (Array.isArray(jsonFiles)) {
// Single file
if (this.path.endsWith('.json')) {
const jsonFile = await this.fetchJsonFile(url);

return [
{
type: 'themes',
path: `${SystemFilenames.THEMES}.json`,
data: jsonFile.$themes ?? [],
},
...(jsonFile.$metadata
? [
{
type: 'metadata' as const,
path: `${SystemFilenames.METADATA}.json`,
data: jsonFile.$metadata,
},
]
: []),
...(
Object.entries(jsonFile).filter(([key]) => !Object.values<string>(SystemFilenames).includes(key)) as [
string,
AnyTokenSet<false>,
][]
).map<RemoteTokenStorageFile>(([name, tokenSet]) => ({
name,
type: 'tokenSet',
path: `${name}.json`,
data: tokenSet,
})),
];
}

// Multi file when it is enabled
if (this.flags.multiFileEnabled) {
const jsonFiles = await this.fetchJsonFilesFromDirectory(url);

const jsonFileContents = await Promise.all(
jsonFiles.map((file: any) => fetch(file.links.self.href, {
headers: {
Expand Down Expand Up @@ -225,36 +277,8 @@ export class BitbucketTokenStorage extends GitTokenStorage {
data: parsed as AnyTokenSet<false>,
};
});
} if (jsonFiles) {
const parsed = jsonFiles as GitSingleFileObject;
return [
{
type: 'themes',
path: `${this.path}/${SystemFilenames.THEMES}.json`,
data: parsed.$themes ?? [],
},
...(parsed.$metadata
? [
{
type: 'metadata' as const,
path: this.path,
data: parsed.$metadata,
},
]
: []),
...(
Object.entries(parsed).filter(([key]) => !Object.values<string>(SystemFilenames).includes(key)) as [
string,
AnyTokenSet<false>,
][]
).map<RemoteTokenStorageFile>(([name, tokenSet]) => ({
name,
type: 'tokenSet',
path: `${this.path}/${name}.json`,
data: tokenSet,
})),
];
}

return {
errorMessage: ErrorMessages.VALIDATION_ERROR,
};
Expand Down Expand Up @@ -302,24 +326,33 @@ export class BitbucketTokenStorage extends GitTokenStorage {

const data = new FormData();

const url = `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/src/${branch}/`;
const existingFiles = await this.fetchJsonFilesFromDirectory(url);

const existingTokenSets: Record<string, boolean> = {};
if (Array.isArray(existingFiles)) {
existingFiles.forEach((file) => {
if (file.path.endsWith('.json') && !file.path.startsWith('$')) {
const tokenSetName = file.path.replace('.json', '');
existingTokenSets[tokenSetName] = true;
const normalizedPath = compact(this.path.split('/')).join('/');
let deletedTokenSets: string[] = [];

if (!normalizedPath.endsWith('.json') && this.flags.multiFileEnabled) {
try {
const url = `https://api.bitbucket.org/2.0/repositories/${owner}/${repo}/src/${branch}/${normalizedPath}`;
const existingFiles = await this.fetchJsonFilesFromDirectory(url);

const existingTokenSets: Record<string, boolean> = {};
if (Array.isArray(existingFiles)) {
existingFiles.forEach((file) => {
if (file.path.endsWith('.json') && !file.path.startsWith('$')) {
const tokenSetName = file.path.replace('.json', '');
existingTokenSets[tokenSetName] = true;
}
});
}
});
}

const localTokenSets = Object.keys(files);
const localTokenSets = Object.keys(files);

const deletedTokenSets = Object.keys(existingTokenSets).filter(
(tokenSet) => !localTokenSets.includes(tokenSet) && !tokenSet.startsWith('$'),
);
deletedTokenSets = Object.keys(existingTokenSets).filter(
(tokenSet) => !localTokenSets.includes(tokenSet) && !tokenSet.startsWith('$'),
);
} catch (e) {
// Do nothing as the folder is not yet created
}
}

// @README the files object is Record<string, string> here
// with the key equal to the filename and the value equal to the new content
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,14 @@ describe('BitbucketTokenStorage', () => {
});

it('can read from Git in single file format', async () => {
storageProvider.changePath('global.json');

mockFetch
.mockImplementationOnce(() => Promise.resolve({
ok: true,
json: () => Promise.resolve({
values: [
{ path: '$themes.json', type: 'commit_file', links: { self: { href: 'https://api.bitbucket.org/file/$themes.json' } } },
{ path: 'global.json', type: 'commit_file', links: { self: { href: 'https://api.bitbucket.org/file/global.json' } } },
],
next: null, // No further pagination needed for this test
$themes: [],
global: { red: { name: 'red', type: 'color', value: '#ff0000' } },
}),
}))
.mockImplementationOnce(() => Promise.resolve({
Expand All @@ -139,7 +138,7 @@ describe('BitbucketTokenStorage', () => {
{
path: '$themes.json',
type: 'themes',
data: { $themes: [] },
data: [],
},
{
path: 'global.json',
Expand All @@ -156,7 +155,7 @@ describe('BitbucketTokenStorage', () => {
]);

expect(mockFetch).toHaveBeenCalledWith(
`https://api.bitbucket.org/2.0/repositories/${storageProvider.owner}/${storageProvider.repository}/src/${storageProvider.branch}/?pagelen=100`,
`https://api.bitbucket.org/2.0/repositories/${storageProvider.owner}/${storageProvider.repository}/src/${storageProvider.branch}/global.json`,
{
headers: {
Authorization: `Basic ${btoa('myusername:mock-secret')}`,
Expand Down
Loading