Skip to content

Commit

Permalink
refactor parseOrigin
Browse files Browse the repository at this point in the history
@janfjohannes Are you sure the findRepoRoot / openRepository are working correctly in this case? Please check the test for the return values.
  • Loading branch information
janfjohannes committed Apr 3, 2024
1 parent b412a7b commit cfbf4ec
Show file tree
Hide file tree
Showing 12 changed files with 998 additions and 208 deletions.
18 changes: 7 additions & 11 deletions inlang/source-code/cli/src/commands/open/editor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@ import { exec } from "node:child_process"
import { Command } from "commander"
import { log } from "../../utilities/log.js"
import fs from "node:fs/promises"
import { findRepoRoot, _listRemotes } from "@lix-js/client"
import { parseOrigin } from "@inlang/telemetry"
import { findRepoRoot, openRepository } from "@lix-js/client"
import type { NodeishFilesystem } from "@lix-js/fs"

export const editor = new Command()
Expand Down Expand Up @@ -31,15 +30,9 @@ export async function editorCommandAction(args: {
return
}

// _listReomotes deprecated, open repo and use repo.listRemotes
const remotes = await _listRemotes({
fs: args.nodeishFs,
dir: repoRoot?.replace("file://", ""),
})

const origin = parseOrigin({ remotes })
const repo = await openRepository(repoRoot, { nodeishFs: args.nodeishFs })
const origin = await repo.getOrigin()

// const origin = parse
// Print out the remote URL
args.logger.info(`Origin URL: ${origin}`)

Expand Down Expand Up @@ -82,7 +75,10 @@ export async function editorCommandAction(args: {
})
}

const parseGithubUrl = (url: string): string | undefined => {
const parseGithubUrl = (url: string | undefined): string | undefined => {
if (!url) {
return undefined
}
const regex = /^(?:https?:\/\/)?(?:www\.)?github\.com\/([\w-]+\/[\w-]+)(?:\.git)?$/
const match = url.match(regex)

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* Gets the git origin url of the currently opened repository.
*/

import { findRepoRoot, openRepository } from "@lix-js/client"
import type { NodeishFilesystem } from "@lix-js/fs"

export async function _getGitOrigin({
fs,
workspaceRoot,
}: {
fs: NodeishFilesystem
workspaceRoot: string | undefined
}) {
try {
const repoRoot = await findRepoRoot({
nodeishFs: fs,
path: workspaceRoot || "",
})

if (!repoRoot) {
console.error("Failed to find repository root.")
return
}
const repo = await openRepository(repoRoot, { nodeishFs: fs })
return repo.getOrigin()
} catch (e) {
return undefined
}
}
Original file line number Diff line number Diff line change
@@ -1,40 +1,28 @@
import { describe, it, expect, vi, beforeEach } from "vitest"
import { getGitOrigin } from "./getGitOrigin.js"
import * as lixClient from "@lix-js/client"
import { describe, it, expect } from "vitest"
import { createNodeishMemoryFs, fromSnapshot as loadSnapshot, type Snapshot } from "@lix-js/fs"
import { readFileSync } from "node:fs"
import { resolve } from "node:path"
import { _getGitOrigin } from "./_getGitOrigin.js"

// Mocks
vi.mock("vscode", () => ({
workspace: {
workspaceFolders: [{ uri: { fsPath: "mock/path" } }],
},
}))
vi.mock("@lix-js/client", () => ({
findRepoRoot: vi.fn().mockResolvedValue("mock/root"),
_listRemotes: vi.fn().mockResolvedValue([{ url: "git@github.com:user/repo.git" }]),
}))
vi.mock("node:fs/promises", () => ({}))
vi.mock("@inlang/telemetry", () => ({
parseOrigin: vi.fn().mockReturnValue("https://github.com/user/repo"),
}))
const nodeishFs = createNodeishMemoryFs()

describe("getGitOrigin", () => {
beforeEach(() => {
vi.clearAllMocks()
// @ts-expect-error
lixClient.findRepoRoot.mockResolvedValue("mock/root")
// @ts-expect-error
lixClient._listRemotes.mockResolvedValue([{ url: "git@github.com:user/repo.git" }])
const ciTestRepo: Snapshot = JSON.parse(
readFileSync(resolve(__dirname, "../../../test/mocks/ci-test-repo.json"), {
encoding: "utf-8",
})
)

loadSnapshot(nodeishFs, ciTestRepo)

it("should return the parsed git origin URL", async () => {
const origin = await getGitOrigin()
expect(origin).toEqual("https://github.com/user/repo")
describe("getGitOrigin", () => {
it("should return the parsed git origin URL when workspace is present", async () => {
const origin = await _getGitOrigin({ fs: nodeishFs, workspaceRoot: "src" })
expect(origin).toEqual("github.com/inlang/ci-test-repo.git")
})

it("should handle errors and return undefined", async () => {
// @ts-expect-error
lixClient.findRepoRoot.mockRejectedValueOnce(new Error("Mock error"))
const origin = await getGitOrigin()
it("should handle errors and return undefined when no workspace folder is found", async () => {
await nodeishFs.rm(".git", { recursive: true })
const origin = await _getGitOrigin({ fs: nodeishFs, workspaceRoot: "src" })
expect(origin).toBeUndefined()
})
})
Original file line number Diff line number Diff line change
@@ -1,29 +1,13 @@
/**
* Gets the git origin url of the currently opened repository.
* Gets the git origin url of the currently opened repository. Wrapper around _getGitOrigin.ts to allow testing with functional code
*/

import { parseOrigin } from "@inlang/telemetry"
import { findRepoRoot, _listRemotes } from "@lix-js/client"
import { _getGitOrigin } from "./_getGitOrigin.js"

import * as vscode from "vscode"
import * as fs from "node:fs/promises"

export async function getGitOrigin() {
try {
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath

// FIXME _listRemotes is deprecated. openRepo and then call repo.listRemotes instead!
const remotes = await _listRemotes({
fs,
dir: (
await findRepoRoot({
nodeishFs: fs,
path: workspaceRoot ?? process.cwd(),
})
)?.replace("file://", ""),
})
const gitOrigin = parseOrigin({ remotes })
return gitOrigin
} catch (e) {
return undefined
}
const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath ?? process.cwd()
return _getGitOrigin({ fs, workspaceRoot })
}
835 changes: 835 additions & 0 deletions inlang/source-code/ide-extension/test/mocks/ci-test-repo.json

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ import { PostHog } from "posthog-node"
import type { TelemetryEvents } from "./events.js"

// TODO add a project UUID to the tele.groups internal #196
// import { getGitRemotes } from "../../utils/git.js"
// import { parseOrigin } from "@inlang/telemetry"

// export const gitOrigin = parseOrigin({ remotes: await getGitRemotes() })

const posthog = new PostHog(publicEnv.PUBLIC_POSTHOG_TOKEN ?? "placeholder", {
host: "https://eu.posthog.com",
Expand Down
2 changes: 0 additions & 2 deletions inlang/source-code/telemetry/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
export { telemetryBrowser } from "./implementation/browser.js"
export { telemetryNode } from "./implementation/node.js"

export { parseOrigin } from "./utilities/parseOrigin.js"
77 changes: 0 additions & 77 deletions inlang/source-code/telemetry/src/utilities/parseOrigin.test.ts

This file was deleted.

43 changes: 0 additions & 43 deletions inlang/source-code/telemetry/src/utilities/parseOrigin.ts

This file was deleted.

79 changes: 78 additions & 1 deletion lix/packages/client/src/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,85 @@
import { describe, it, expect } from "vitest"
import { parseLixUri } from "./helpers.js"
import { parseLixUri, parseOrigin } from "./helpers.js"

// TODO: add local uris when implemented: "file://repo"

describe("parseOrigin", () => {
it("should return 'unknown' if the remotes are undefined", () => {
const result = parseOrigin({ remotes: undefined })
expect(result).toBe(undefined)
})

it("should return 'unknown' if the remotes are empty", () => {
const result = parseOrigin({ remotes: [] })
expect(result).toBe(undefined)
})

it("should return 'unknown' if the remotes contain no origin", () => {
const result = parseOrigin({
remotes: [
{
remote: "foreign",
url: "https://example.com",
},
],
})
expect(result).toBe(undefined)
})

it("should return the repo with '.git' at the end ", () => {
const result = parseOrigin({
remotes: [
{
remote: "origin",
url: "https://github.com/example/repo",
},
],
})

expect(result).toBe("github.com/example/repo.git")
})
//the effort to validate the tld is to high at the moment. Because, Rexeg is not reliable and introducing a dependency does not seen worse it.
it.skip("should return unknown if the origin url is invalid ", () => {
const result = parseOrigin({
remotes: [
{
remote: "origin",
url: `https://fcom/f/d.git`,
},
],
})
expect(result).toBe(undefined)
})
it("should origin should not contain signing keys", () => {
const mockSigningKey = "ghp_Ps2aGEWV0jE7hnm32Zo4HfMABCdRVDE0BxMO1"
const result = parseOrigin({
remotes: [
{
remote: "origin",
url: `https://${mockSigningKey}@github.com/peter/neumann.git`,
},
],
})
expect(result.includes(mockSigningKey)).toBe(false)
})

it("should match different origin patterns to one unambigious identifier", () => {
const remotes = [
"https://github.com/example/repo.git",
"git@github.com:example/repo.git",
"username@github.com/example/repo.git",
"https://ghp_Es2aQE4V0jE7hnm59Zo1GfSSDdRVDE0BxMO1@github.com/example/repo.git",
"x-access-token/ghs_bWzL0m50asffasfLa2RmWkuPasd9Mo0jiK0A@github.com/example/repo.git",
"gitlab-ci-token/64_jprnG_nQR5sYNLTp6S3w@github.com/example/repo.git",
]

for (const remote of remotes) {
const result = parseOrigin({ remotes: [{ remote: "origin", url: remote }] })
expect(result).toBe("github.com/example/repo.git")
}
})
})

describe("parse lix uris", () => {
it("parses github uris correctly", () => {
const parseResult = parseLixUri("https://github.com/opral/monorepo")
Expand Down
Loading

0 comments on commit cfbf4ec

Please sign in to comment.