Skip to content

Commit

Permalink
Convert a bunch of things to TypeScript (#49)
Browse files Browse the repository at this point in the history
* TypeScript on a lot of things

* Fix stuff

* Add changesets
  • Loading branch information
emmatown authored and Noviny committed May 21, 2019
1 parent 3066e7e commit 83ba6d3
Show file tree
Hide file tree
Showing 28 changed files with 202 additions and 92 deletions.
4 changes: 4 additions & 0 deletions .changeset/4c29db0e/changes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"releases": [{ "name": "@changesets/cli", "type": "patch" }],
"dependents": []
}
1 change: 1 addition & 0 deletions .changeset/4c29db0e/changes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Convert various modules to TypeScript
10 changes: 10 additions & 0 deletions .changeset/d9b800c5/changes.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"releases": [{ "name": "get-workspaces", "type": "minor" }],
"dependents": [
{
"name": "@changesets/cli",
"type": "patch",
"dependencies": ["get-workspaces"]
}
]
}
1 change: 1 addition & 0 deletions .changeset/d9b800c5/changes.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Export Workspace type
3 changes: 2 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"license": "MIT",
"dependencies": {
"@babel/runtime": "^7.4.4",
"@types/semver": "^6.0.0",
"bolt": "^0.22.1",
"boxen": "^1.3.0",
"chalk": "^2.1.0",
Expand All @@ -40,4 +41,4 @@
"devDependencies": {
"jest-fixtures": "^0.5.0"
}
}
}
2 changes: 1 addition & 1 deletion packages/cli/src/commands/add/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import getChangesetBase from "../../utils/getChangesetBase";
import { printConfirmationMessage } from "./messages";

export default async function add(opts) {
const userConfig = await resolveUserConfig({ cwd: opts.cwd });
const userConfig = await resolveUserConfig(opts.cwd);
const userchangesetOptions =
userConfig && userConfig.changesetOptions
? userConfig.changesetOptions
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/bump/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import versionRangeToRangeType from "../../utils/bolt-replacements/versionRangeT
import { defaultConfig } from "../../utils/constants";

export default async function version(opts) {
let userConfig = await resolveConfig(opts);
let userConfig = await resolveConfig(opts.cwd);
userConfig =
userConfig && userConfig.versionOptions ? userConfig.versionOptions : {};
const config = { ...defaultConfig.versionOptions, ...userConfig, ...opts };
Expand Down
2 changes: 1 addition & 1 deletion packages/cli/src/commands/release/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function logReleases(status, pkgs) {
}

export default async function run(opts) {
const userConfig = await resolveUserConfig({ cwd: opts.cwd });
const userConfig = await resolveUserConfig(opts.cwd);
const userPublishOptions =
userConfig && userConfig.publishOptions ? userConfig.publishOptions : {};

Expand Down
8 changes: 1 addition & 7 deletions packages/cli/src/commands/status/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,7 @@ export default async function getStatus({
output,
...opts
}) {
let userConfig = await resolveConfig({
cwd,
sinceMaster,
verbose,
output,
...opts
});
let userConfig = await resolveConfig(cwd);
userConfig =
userConfig && userConfig.versionOptions ? userConfig.versionOptions : {};
const config = { ...defaultConfig.versionOptions, ...userConfig, ...opts };
Expand Down
11 changes: 9 additions & 2 deletions packages/cli/src/utils/bolt-replacements/getWorkspaces.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
import getWorkspaces from "get-workspaces";

export default function(opts: { cwd: string }) {
return getWorkspaces({ tools: ["yarn", "bolt", "root"], ...opts });
export default async function(opts: { cwd: string }) {
let workspaces = await getWorkspaces({
tools: ["yarn", "bolt", "root"],
...opts
});
if (workspaces === null) {
return [];
}
return workspaces;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// @ts-ignore
import getDependentsGraph from "./getDependentsGraph";
import getWorkspaces from "./getWorkspaces";
// @ts-ignore
import publishPackages from "./publishPackages";
// @ts-ignore
import getDependencyGraph from "./getDependencyGraph";

export {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import pkgDir from "pkg-dir";
import path from "path";

export const pkgPath = pkgDir.sync(__dirname);
export const pkgPath = path.dirname(
require.resolve("@changesets/cli/package.json")
);

export const defaultConfig = require(path.join(
pkgPath,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
function maxType(types) {
import { Changeset, BumpType } from "../types";

function maxType(types: Array<BumpType>) {
if (types.includes("major")) return "major";
if (types.includes("minor")) return "minor";
if (types.includes("patch")) return "patch";
return "none";
}

export default function flattenReleases(changesets, allLinkedPackages) {
export default function flattenReleases(
changesets: Array<Changeset>,
allLinkedPackages: Array<Array<string>>
) {
const flatChangesets = changesets
.map(changeset => [
...changeset.releases.map(release => ({
Expand All @@ -22,15 +27,30 @@ export default function flattenReleases(changesets, allLinkedPackages) {
}))
])
.reduce((acc, a) => [...acc, ...a], []) // flatten
.reduce((acc, release) => {
.reduce<{
[key: string]: Array<{
name: string;
type: BumpType;
commit: string;
id: string;
}>;
}>((acc, release) => {
if (!acc[release.name]) {
acc[release.name] = [];
}
acc[release.name].push(release);
return acc;
}, {});

const flatReleases = new Map(
const flatReleases = new Map<
string,
{
name: string;
type: BumpType;
commits: Array<string>;
changesets: Array<string>;
}
>(
Object.entries(flatChangesets).map(([name, releases]) => [
name,
{
Expand All @@ -43,7 +63,7 @@ export default function flattenReleases(changesets, allLinkedPackages) {
);

for (const linkedPackages of allLinkedPackages) {
const allBumpTypes = [];
const allBumpTypes: Array<BumpType> = [];
for (let linkedPackage of linkedPackages) {
let release = flatReleases.get(linkedPackage);
if (release) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import semver from "semver";
import flattenChangesets from "./flattenChangesets";
import { Changeset, BumpType } from "../types";
import { Workspace } from "get-workspaces";
/*
This flattens an array of Version objects into one object that can be used to create the changelogs
and the publish commit messages.
Expand Down Expand Up @@ -36,8 +38,8 @@ import flattenChangesets from "./flattenChangesets";
*/

export default function createRelease(
changesets,
allPackages,
changesets: Array<Changeset>,
allPackages: Array<Workspace>,
allLinkedPackages = []
) {
// First, combine all the changeset.releases into one useful array
Expand All @@ -47,7 +49,11 @@ export default function createRelease(
let currentVersions = new Map();

for (let pkg of allPackages) {
currentVersions.set(pkg.name, pkg ? pkg.config.version : null);
currentVersions.set(
pkg.name,
// @ts-ignore
pkg.config.version !== undefined ? pkg.config.version : null
);
}

for (let linkedPackages of allLinkedPackages) {
Expand All @@ -63,19 +69,26 @@ export default function createRelease(
}
}

const allReleases = flattenedChangesets
// do not update none packages
.filter(release => release.type !== "none")
// get the current version for each package
.map(release => ({
...release,
version: currentVersions.get(release.name)
}))
// update to new version for each package
.map(release => ({
...release,
version: semver.inc(release.version, release.type)
}));
const allReleases: Array<{
name: string;
type: BumpType;
changesets: Array<string>;
commits: Array<string>;
version?: string | null;
}> = [];

for (let flattenedChangeset of flattenedChangesets) {
if (flattenedChangeset.type === "none") {
continue;
}
allReleases.push({
...flattenedChangeset,
version: semver.inc(
currentVersions.get(flattenedChangeset.name),
flattenedChangeset.type
)
});
}

return {
releases: allReleases.filter(release => release.version !== null),
Expand Down
7 changes: 0 additions & 7 deletions packages/cli/src/utils/getChangesetBase.js

This file was deleted.

7 changes: 7 additions & 0 deletions packages/cli/src/utils/getChangesetBase.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import path from "path";
import { getProjectDirectory } from "./getProjectDirectory";

export default async function getChangesetBase(cwd: string) {
const dir = await getProjectDirectory(cwd);
return path.resolve(dir, ".changeset");
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ import fs from "fs-extra";
import path from "path";

import * as git from "./git";
import { Changeset } from "./types";

// TODO take in cwd, and fetch changesetBase ourselves
export default async function getChangesets(changesetBase, sinceMasterOnly) {
export default async function getChangesets(
changesetBase: string,
sinceMasterOnly: boolean
): Promise<Array<Changeset>> {
if (!fs.existsSync(changesetBase)) {
throw new Error("There is no .changeset directory in this project");
}
Expand Down
9 changes: 9 additions & 0 deletions packages/cli/src/utils/getProjectDirectory.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import pkgDir from "pkg-dir";

export async function getProjectDirectory(cwd: string) {
const projectDir = await pkgDir(cwd);
if (!projectDir) {
throw new Error("Could not find project directory");
}
return projectDir;
}
35 changes: 22 additions & 13 deletions packages/cli/src/utils/git.js → packages/cli/src/utils/git.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
import spawn from "projector-spawn";
import path from "path";
import pkgDir from "pkg-dir";
import { getProjectDirectory } from "./getProjectDirectory";
// @ts-ignore
import * as bolt from "./bolt-replacements";

async function getMasterRef(cwd) {
async function getMasterRef(cwd: string) {
const gitCmd = await spawn("git", ["rev-parse", "master"], { cwd });
return gitCmd.stdout.trim().split("\n")[0];
}

async function add(pathToFile, cwd) {
async function add(pathToFile: string, cwd: string) {
const gitCmd = await spawn("git", ["add", pathToFile], { cwd });
return gitCmd.code === 0;
}

async function commit(message, cwd) {
async function commit(message: string, cwd: string) {
const gitCmd = await spawn(
"git",
["commit", "-m", message, "--allow-empty"],
Expand All @@ -23,14 +24,14 @@ async function commit(message, cwd) {
}

// used to create a single tag at a time for the current head only
async function tag(tagStr, cwd) {
async function tag(tagStr: string, cwd: string) {
// NOTE: it's important we use the -m flag otherwise 'git push --follow-tags' wont actually push
// the tags
const gitCmd = await spawn("git", ["tag", tagStr, "-m", tagStr], { cwd });
return gitCmd.code === 0;
}

async function getCommitThatAddsFile(gitPath, cwd) {
async function getCommitThatAddsFile(gitPath: string, cwd: string) {
const gitCmd = await spawn(
"git",
["log", "--reverse", "--max-count=1", "--pretty=format:%h", "-p", gitPath],
Expand All @@ -41,7 +42,11 @@ async function getCommitThatAddsFile(gitPath, cwd) {
return gitCmd.stdout.split("\n")[0];
}

async function getChangedFilesSince(ref, cwd, fullPath = false) {
async function getChangedFilesSince(
ref: string,
cwd: string,
fullPath = false
) {
// First we need to find the commit where we diverged from `ref` at using `git merge-base`
let cmd = await spawn("git", ["merge-base", ref, "HEAD"], { cwd });
const divergedAt = cmd.stdout.trim();
Expand All @@ -53,7 +58,10 @@ async function getChangedFilesSince(ref, cwd, fullPath = false) {
}

// below are less generic functions that we use in combination with other things we are doing
async function getChangedChangesetFilesSinceMaster(cwd, fullPath = false) {
async function getChangedChangesetFilesSinceMaster(
cwd: string,
fullPath = false
) {
const ref = await getMasterRef(cwd);
// First we need to find the commit where we diverged from `ref` at using `git merge-base`
let cmd = await spawn("git", ["merge-base", ref, "HEAD"], { cwd });
Expand All @@ -72,19 +80,20 @@ async function getChangedChangesetFilesSinceMaster(cwd, fullPath = false) {
return files.map(file => path.resolve(cwd, file));
}

async function getChangedPackagesSinceCommit(commitHash, cwd) {
async function getChangedPackagesSinceCommit(commitHash: string, cwd: string) {
const changedFiles = await getChangedFilesSince(commitHash, cwd, true);
const projectDir = await pkgDir(cwd);
const projectDir = await getProjectDirectory(cwd);
const workspaces = await bolt.getWorkspaces({ cwd });
const allPackages = workspaces.map(pkg => ({
...pkg,
relativeDir: path.relative(projectDir, pkg.dir)
}));

const fileNameToPackage = fileName =>
const fileNameToPackage = (fileName: string) =>
allPackages.find(pkg => fileName.startsWith(pkg.dir + path.sep));

const fileExistsInPackage = fileName => !!fileNameToPackage(fileName);
const fileExistsInPackage = (fileName: string) =>
!!fileNameToPackage(fileName);

return (
changedFiles
Expand All @@ -100,7 +109,7 @@ async function getChangedPackagesSinceCommit(commitHash, cwd) {
// it wont include staged/unstaged changes
//
// Don't use this function in master branch as it returns nothing in that case.
async function getChangedPackagesSinceMaster(cwd) {
async function getChangedPackagesSinceMaster(cwd: string) {
const masterRef = await getMasterRef(cwd);
return getChangedPackagesSinceCommit(masterRef, cwd);
}
Expand Down
Loading

0 comments on commit 83ba6d3

Please sign in to comment.