Skip to content

Commit

Permalink
refactor: remove comment-only files in withModuleSelection()
Browse files Browse the repository at this point in the history
  • Loading branch information
Yogu committed Sep 13, 2024
1 parent 350a9f6 commit 691f3e0
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
47 changes: 47 additions & 0 deletions spec/project/select-modules-in-sources.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,53 @@ describe('selectModulesInProjectSource', () => {
expect(result.getModel().modules).to.deep.equal([]);
});

it('removes files that become comment-only', () => {
const project = new Project({
sources: [
new ProjectSource(
'modules.json',
JSON.stringify({
modules: ['module1', 'module2', 'module3', 'extra1', 'extra2'],
}),
),
gql`
# a comment in the keeper file
type Keeper @rootEntity @modules(in: "module1", includeAllFields: true) {
key: String @key
}
`.loc!.source,
gql`
# a comment in the discard file
type Discard @rootEntity @modules(in: "extra2", includeAllFields: true) {
key: String @key
}
`.loc!.source,
// will also remove this one because we're throwing away comment-only file when
// parsing a project. Documenting that behavior in this test case, but it's
// probably fine either way
{
name: 'empty.graphqls',
body: "# a file that's already comment-only",
},
],
modelOptions: { withModuleDefinitions: true },
});
expectToBeValid(project);

const result = project.withModuleSelection(['module1', 'module2'], {
removeModuleDeclarations: true,
});
expectToBeValid(result);
expect(result.sources.map((s) => s.body)).to.deep.equal([
`
# a comment in the keeper file
type Keeper @rootEntity {
key: String @key
}
`,
]);
});

it('removes the modules part in an object file with modules and something else', () => {
const project = new Project({
sources: [
Expand Down
10 changes: 10 additions & 0 deletions src/project/select-modules-in-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { findDirectiveWithName } from '../schema/schema-utils';
import { Project, ProjectOptions } from './project';
import { ProjectSource } from './source';
import { isReadonlyArray } from '../utils/utils';
import { isCommentOnlySource } from '../graphql/is-comment-only-source';

export interface ModuleSelectionOptions {
/**
Expand Down Expand Up @@ -255,6 +256,10 @@ function selectModulesInGraphQLSource({
}
}

if (!changes) {
return source.body;
}

let currentPosition = 0;
let output = '';
for (let i = 0; i <= changes.length; i++) {
Expand All @@ -275,6 +280,11 @@ function selectModulesInGraphQLSource({
}
}

// if we removed everything except comments, delete the file
if (isCommentOnlySource(output)) {
return undefined;
}

return output;
}

Expand Down

0 comments on commit 691f3e0

Please sign in to comment.