Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
ctx: HandlerContext,
params: this): Promise {
const sdmGoal = event.data.SdmGoal[0] as SdmGoal;
if (!isGoalRelevant(sdmGoal)) {
logger.debug(`Goal ${sdmGoal.name} skipped because not relevant for this SDM`);
return Success;
}
const commit = await fetchCommitForSdmGoal(ctx, sdmGoal);
const status: StatusForExecuteGoal.Fragment = convertForNow(sdmGoal, commit);
// this should not happen but it does: automation-api#395
if (sdmGoal.state !== "requested") {
logger.warn(`Goal ${sdmGoal.name}: Received '${sdmGoal.state}' on ${status.context}, while looking for 'requested'`);
return Success;
}
if (sdmGoal.fulfillment.method !== "SDM fulfill on requested") {
logger.info("Goal %s: Implementation method is '%s'; not fulfilling", sdmGoal.name, sdmGoal.fulfillment.method);
return Success;
}
logger.info("Executing FulfillGoalOnRequested with '%s'", sdmGoal.fulfillment.name); // take this out when automation-api#395 is fixed
const {goal, goalExecutor, logInterpreter} = this.implementationMapper.findImplementationBySdmGoal(sdmGoal);
const log = await this.logFactory(ctx, sdmGoal);
const progressLog = new WriteToAllProgressLog(sdmGoal.name, new LoggingProgressLog(sdmGoal.name, "debug"), log);
const addressChannels = addressChannelsFor(commit.repo, ctx);
const id = params.repoRefResolver.repoRefFromSdmGoal(sdmGoal, await fetchProvider(ctx, sdmGoal.repo.providerId));
if (!!(fp as any).entropy) {
return bandFor(EntropySizeBands, (fp as any).entropy, {
casing: BandCasing.Sentence,
includeNumber: false,
});
} else {
return undefined;
}
},
});
}
// driftTree.tree = flattenSoleFingerprints(driftTree.tree);
fillInDriftTreeAspectNames(aspectRegistry, driftTree.tree);
return res.json(driftTree);
} catch (err) {
logger.warn("Error occurred getting drift report: %s %s", err.message, err.stack);
next(err);
}
});
}
if (goalEvent.state === SdmGoalState.in_process) {
return;
}
if (goalEvent.state === SdmGoalState.canceled && !(await cancelableGoal(goalEvent, gi.configuration))) {
return;
}
const selector = `atomist.com/goal-set-id=${goalEvent.goalSetId},atomist.com/creator=${sanitizeName(this.sdm.configuration.name)}`;
let jobs;
try {
jobs = await listJobs(selector);
} catch (e) {
logger.warn(`Failed to read k8s jobs: ${prettyPrintError(e)}`);
return;
}
logger.debug(
`Found k8s jobs for goal set '${goalEvent.goalSetId}': '${
jobs.map(j => `${j.metadata.namespace}:${j.metadata.name}`).join(", ")}'`);
const goalJobs = jobs.filter(j => {
const annotations = j.metadata.annotations;
if (!!annotations && !!annotations["atomist.com/sdm"]) {
const sdmAnnotation = JSON.parse(annotations["atomist.com/sdm"]);
return sdmAnnotation.goal.uniqueName === goalEvent.uniqueName;
}
return false;
});
const prefs: PreferenceStore = configurationValue("sdm.preferenceStoreFactory")(ctx);
for (const org of orgs) {
const analyzed = await prefs.get(preferenceKey(org.name), { scope: PreferenceScope.Sdm, defaultValue: false });
if (!analyzed || rerun) {
try {
await createJob({
command: calculateFingerprintTask([], []),
parameters: org.tasks,
name: `OrganizationAnalysis/${org.providerId}/${org.name}`,
description: `Analyzing repositories in ${bold(org.name)}`,
},
ctx);
await prefs.put(preferenceKey(org.name), true, { scope: PreferenceScope.Sdm });
} catch (e) {
logger.warn("Failed to create job for org '%s': %s", org.name, e.message);
}
}
}
}
async function dedup(key: string, f: () => Promise): Promise {
if (running[key]) {
logger.warn("deploy was called twice for " + key);
return Promise.resolve();
}
running[key] = true;
const promise = f().then(t => {
running[key] = undefined;
return t;
});
return promise;
}
public async afterPersist(p: Project): Promise {
try {
const gitStatus = await (p as GitProject).gitStatus();
const sha = gitStatus.sha;
if (!sha) {
throw new Error("Sha is not available");
}
logger.info("Setting status %j on sha %s for %j", this.status, sha, p.id);
return createStatus(this.creds, {
...p.id,
sha,
} as GitHubRepoRef,
this.status);
} catch (err) {
logger.warn("Unable to get git status for %j. Possibly a deleted repo", p.id);
}
}
}
private async cleanup(p: string, keep: boolean): Promise {
if (keep) {
return;
}
try {
await fs.remove(p);
} catch (e) {
logger.warn(`Failed to remove '${p}': ${e.message}`);
}
}
}
async function dedup(key: string, f: () => Promise): Promise {
if (running[key]) {
logger.warn("This op was called twice for " + key);
return Promise.resolve();
}
running[key] = true;
const promise = f().then(t => {
running[key] = undefined;
return t;
});
return promise;
}
} catch (err) {
try {
await execPromise("git", ["fetch", "--unshallow", "--no-tags"], { cwd: project.baseDir });
return await gitDiff(sha, commitCount, project);
} catch (err) {
logger.warn("Error diffing project %j since '%s': %s", project.id, sha, err.message);
try {
const gs = await project.gitStatus();
logger.warn("Git status sha '%s' and branch '%s'", gs.sha, gs.branch);
const timeOfLastChange = await execPromise("ls", ["-ltr", "."], { cwd: project.baseDir });
logger.info("Files with dates: " + timeOfLastChange.stdout);
} catch (err) {
logger.warn("Error while trying extra logging: " + err.stack);
}
return undefined;
}
}
}
const result = {
...preHookResult,
...goalResult,
...postHookResult,
};
await notifyGoalExecutionListeners({
...inProcessGoalEvent,
state: SdmGoalState.success,
}, result);
logger.info("Goal '%s' completed with: %j", goalEvent.uniqueName, result);
await markStatus({ context, goalEvent, goal, result, progressLogUrl: progressLog.url });
return { ...result, code: 0 };
} catch (err) {
logger.warn("Error executing goal '%s': %s", goalEvent.uniqueName, err.message);
const result = handleGitRefErrors({ code: 1, ...(err.result || {}) }, err);
await notifyGoalExecutionListeners({
...inProcessGoalEvent,
state: result.state || SdmGoalState.failure,
}, result, err);
await reportGoalError({
goal, implementationName, addressChannels, progressLog, id, logInterpreter,
}, err);
await markStatus({
context,
goalEvent,
goal,
result,
error: err,
progressLogUrl: progressLog.url,
});