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

auto generate contributors if a contributors list exists but none are… #1575

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
34 changes: 34 additions & 0 deletions plugins/all-contributors/__tests__/all-contributors.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as Auto from "@auto-it/core";
import generateReadme from "all-contributors-cli/dist/generate";
import addContributor from "all-contributors-cli/dist/contributors";
import {
makeHooks,
Expand All @@ -11,6 +12,7 @@ import env from "env-ci";

import AllContributors from "../src";

const generateMock = jest.fn();
const addContributorMock = jest.fn();
const envMock = jest.fn();
const gitShow = jest.fn();
Expand All @@ -25,6 +27,9 @@ jest.mock("env-ci");
jest.mock("child_process");
jest.mock("all-contributors-cli/dist/contributors");
jest.mock("all-contributors-cli/dist/generate");

// @ts-ignore
generateReadme.mockImplementation(generateMock);
// @ts-ignore
addContributor.mockImplementation(addContributorMock);
// @ts-ignore
Expand Down Expand Up @@ -546,6 +551,35 @@ describe("All Contributors Plugin", () => {
expect(addContributorMock).not.toHaveBeenCalled();
});

test("should initialize contributors if not already initialized", async () => {
const releasedLabel = new AllContributors();
const autoHooks = makeHooks();
mockRead(
'{ "contributors": [ { "login": "Jeff", "contributions": ["code"] } ], "files": ["README.md"]}'
);

mockRead(
"<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --><!-- prettier-ignore-start -->\n<!-- markdownlint-disable -->\n<!-- markdownlint-restore -->\n<!-- prettier-ignore-end -->\n<!-- ALL-CONTRIBUTORS-LIST:END -->"
);

releasedLabel.apply({ hooks: autoHooks, logger: dummyLog() } as Auto.Auto);

await autoHooks.afterAddToChangelog.promise({
bump: Auto.SEMVER.patch,
currentVersion: "0.0.0",
lastRelease: "0.0.0",
releaseNotes: "",
commits: [
makeCommitFromMsg("Do the thing", {
files: ["src/index.ts"],
username: "Jeff",
}),
],
});

expect(generateMock).toHaveBeenCalled();
});

describe("parseCommit", () => {
test("should do nothing if no extra contributions are found", async () => {
const releasedLabel = new AllContributors();
Expand Down
112 changes: 71 additions & 41 deletions plugins/all-contributors/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ interface AllContributorsRc {
/** All of the current contributors */
contributors: Contributor[];
/** Files to generate a markdown table of contributors in */
files: string[];
files?: string[];
}

const defaultOptions: IAllContributorsPluginOptions = {
Expand Down Expand Up @@ -173,20 +173,44 @@ function getExtraContributors(body?: string) {
return authorContributions;
}

/** Determine which files need to display contributors and generate contributors */
function generateContributorReadme(config: AllContributorsRc, contributors: any) {
return (config.files || ["README.md"]).map(async (file) => {
const oldReadMe = fs.readFileSync(file, {
encoding: "utf-8",
});
const newReadMe = await generateReadme(
{
contributorsPerLine: 7,
imageSize: 100,
...config,
contributors,
},
contributors,
oldReadMe
);
fs.writeFileSync(file, newReadMe);
})
}

kendallgassner marked this conversation as resolved.
Show resolved Hide resolved
/** Automatically add contributors as changelogs are produced. */
export default class AllContributorsPlugin implements IPlugin {
/** The name of the plugin */
name = "all-contributors";

/** The options of the plugin */
readonly options: Required<IAllContributorsPluginOptions>;
/** Has the Readme been initialized */
private generatedReadme: boolean;

/** Initialize the plugin with it's options */
constructor(options: IAllContributorsPluginOptions = {}) {
this.options = {
exclude: [...(defaultOptions.exclude || []), ...(options.exclude || [])],
types: { ...defaultOptions.types, ...options.types },
};

this.generatedReadme = false;
}

/** Tap into auto plugin points. */
Expand Down Expand Up @@ -241,40 +265,38 @@ export default class AllContributorsPlugin implements IPlugin {
const message = endent`
# Extra Contributions

${
hasValidTypes
? endent`
${hasValidTypes
? endent`
The following contributions will be added to all-contributors (as well as any code contributions) when this PR is released :tada::

${Object.entries(extra)
.map(([username, contributions]) => {
const validContributions = [...contributions].filter(
isContribution
);

if (!validContributions.length) {
return "";
}

return `- @${username} - ${validContributions.join(", ")}`;
})
.filter(Boolean)
.join("\n")}
.map(([username, contributions]) => {
const validContributions = [...contributions].filter(
isContribution
);

if (!validContributions.length) {
return "";
}

return `- @${username} - ${validContributions.join(", ")}`;
})
.filter(Boolean)
.join("\n")}
`
: "No valid contribution types found!"
: "No valid contribution types found!"
}

${
unknownTypes.length
? endent`
${unknownTypes.length
? endent`
## Unknown Contribution Types

We found some unknown contribution types in your PR body!
These contributions will not be counted and you should fix them.

${unknownTypes.map((type) => `- \`${type}\``)}
`
: ""
: ""
}
`;

Expand All @@ -296,7 +318,7 @@ export default class AllContributorsPlugin implements IPlugin {
try {
// Try to get sub-packages
packages = [...packages, ...(await getLernaPackages())];
} catch (error) {}
} catch (error) { }

// Go through each package and update code contributions
await packages.reduce(async (last, { name, path }) => {
Expand Down Expand Up @@ -375,6 +397,8 @@ export default class AllContributorsPlugin implements IPlugin {
});
}



/** Update the contributors rc for a package. */
private async updateContributors(auto: Auto, commits: IExtendedCommit[]) {
const config = getRcFile(auto);
Expand Down Expand Up @@ -485,31 +509,37 @@ export default class AllContributorsPlugin implements IPlugin {
username,
Array.from(newContributions).join(",")
);

this.generatedReadme = true;
// Update files that contain contributors table
await Promise.all(
(config.files || ["README.md"]).map(async (file) => {
const oldReadMe = fs.readFileSync(file, {
encoding: "utf-8",
});
const newReadMe = await generateReadme(
{
contributorsPerLine: 7,
imageSize: 100,
...config,
contributors,
},
contributors,
oldReadMe
);
fs.writeFileSync(file, newReadMe);
})
generateContributorReadme(config, contributors)
);
} else {
}
else {
auto.logger.verbose.warn(`"${username}" had no new contributions...`);
}
}

if (config.contributors.length && !this.generatedReadme) {
// if the all-contributors has not been generated ... generate it
try {
// test if the first file in the list of files has been init
const file = path.join(process.cwd(), (config.files ? config.files[0] : "README.md"));

const displayFile = file ? fs.readFileSync(file, 'utf8') : '';

const notInitalized = displayFile.indexOf(
'<!-- markdownlint-disable -->\n<!-- markdownlint-restore -->'
);

if (notInitalized && file) {
await Promise.all(
generateContributorReadme(config, undefined)
kendallgassner marked this conversation as resolved.
Show resolved Hide resolved
);
kendallgassner marked this conversation as resolved.
Show resolved Hide resolved
}
} catch { }
}

if (didUpdate) {
auto.logger.log.success("Updated contributors!");
}
Expand Down