Skip to content

Commit 5dc1483

Browse files
committed
💥 Update schema to use array for rules
1 parent 4a21098 commit 5dc1483

10 files changed

Lines changed: 186 additions & 116 deletions

File tree

‎.env.example‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,6 @@ LOG_LEVEL=debug
77

88
# Go to https://smee.io/new set this to the URL that you are redirected to.
99
WEBHOOK_PROXY_URL=
10+
11+
# Relative path of the webhook
12+
WEBHOOK_PATH=

‎.github/sync-up.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
version: "1"
22
rules:
3-
master:
3+
- head: master
44
upstream: wei:master
55
autoMerge: true
66
autoMergeHardReset: true

‎README.md‎

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,22 +4,24 @@
44

55
[![TravisCI](https://travis-ci.com/wei/sync-up.svg?branch=master)](https://travis-ci.com/wei/sync-up)
66
[![Codecov](https://codecov.io/gh/wei/sync-up/branch/master/graph/badge.svg)](https://codecov.io/gh/wei/sync-up)
7-
[![Depfu](https://img.shields.io/depfu/wei/sync-up.svg)](https://depfu.com/github/wei/sync-up)
7+
[![Depfu](https://badges.depfu.com/badges/74c85550f06d7840881eab5756738628/overview.svg)](https://depfu.com/github/wei/sync-up)
88
<br/>
99
[![Probot](https://img.shields.io/badge/built%20with-probot-orange.svg)](https://probot.github.io/)
1010
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
1111
[![jest](https://facebook.github.io/jest/img/jest-badge.svg)](https://github.com/facebook/jest)
1212
[![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://wei.mit-license.org)
1313

14-
> a GitHub App built with [probot](https://github.com/probot/probot) that keeps your repository up-to-date with upstream changes via automatic pull requests.
14+
> 🤖 a GitHub App built with [probot](https://github.com/probot/probot) that keeps your repository up-to-date with upstream changes via automated pull requests.
1515
1616

1717
## Features
1818

19-
1. A pull request is created when a specified upstream is updated (checking periodically).
20-
2. The pull request can be automatically merged.
19+
1. A pull request is created when an upstream is updated (checks hourly).
20+
2. Pull requests can be automatically merged or hard reset to match upstream.
21+
2122
_Upstream must be in the same fork network_
2223

24+
2325
## Setup
2426

2527
Recommended setup:
@@ -28,26 +30,40 @@ Recommended setup:
2830
3. Setup the new branch as Default branch under repository Settings > Branches
2931
4. Add `.github/sync-up.yml` to your default branch.
3032

33+
Most common `sync-up.xml`:
34+
```yaml
35+
version: "1"
36+
rules:
37+
- head: master
38+
upstream: wei:master
39+
autoMerge: true
40+
autoMergeHardReset: true
41+
```
42+
43+
Explained:
3144
```yaml
3245
version: "1"
33-
rules: # Array of branches to sync
34-
master:
35-
upstream: wei:master # Required. Must be in the same fork network
36-
autoMerge: true # Optional, Default: false
37-
autoMergeHardReset: true # Optional, Default: false. Dangerous!! Remove merge commits along with any changes to the specified branch
38-
dev:
46+
rules: # Array of branches to sync
47+
- head: master # Required. Target local branch
48+
upstream: wei:master # Required. Must be in the same fork network.
49+
autoMerge: true # Optional, Default: false
50+
autoMergeHardReset: true # Optional, Default: false DESTRUCTIVE!! Remove merge commits along with any changes to the target local branch
51+
- head: dev
3952
upstream: master
53+
assignees: # Optional
54+
- wei
55+
reviewers: # Optional
56+
- wei
4057
label: "sync-up :arrow_up_down:" # Optional
41-
assignees: # Optional
42-
- wei
43-
reviewers: # Optional
44-
- wei
4558
```
4659
47-
5. Install Sync Up app via https://github.com/apps/sync-up and select only the repos you wish to sync up.
60+
5. Go to `https://sync-up.now.sh/check/:owner/:repo` to validate your `sync-up.yml`.
61+
6. Install Sync Up app via https://github.com/apps/sync-up and select only the repos you wish to sync up.
62+
4863

4964
## Author
5065
[Wei He](https://github.com/wei) _github@weispot.com_
5166

67+
5268
## License
5369
[MIT](https://wei.mit-license.org)

‎index.js‎

Lines changed: 15 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -61,20 +61,30 @@ module.exports = async (robot) => {
6161
return new SyncUp(context.github, context.repo({ logger: robot.log }), config)
6262
}
6363

64-
const app = robot.route('/_')
64+
const app = robot.route()
65+
66+
app.get('/', (req, res) => res.redirect('https://github.com/wei/sync-up#readme'))
6567

6668
app.get('/check/:owner/:repo', (req, res) => {
69+
robot.log.info(`[${req.params.owner}/${req.params.repo}] Checking ${SYNCUP_CONFIG}`)
6770
fetch(`https://api.github.com/repos/${req.params.owner}/${req.params.repo}/contents/.github/${SYNCUP_CONFIG}`)
6871
.then(githubRes => githubRes.json())
6972
.then(json => Buffer.from(json.content, 'base64').toString())
7073
.then(yml => yaml.safeLoad(yml))
7174
.then((config) => {
7275
const { error, value } = schema.validate(config)
7376
if (error) throw error
74-
res.end(JSON.stringify(value, null, 2))
75-
})
76-
.catch((e) => {
77-
res.status(400).end(`File not found or invalid`)
77+
78+
const reqs = value.rules.map(r => new Promise((resolve, reject) => {
79+
fetch(`https://api.github.com/repos/${req.params.owner}/${req.params.repo}/compare/${r.base}...${r.upstream}`)
80+
.then(githubRes => (githubRes.ok ? resolve() : reject(Error(`${r.base}...${r.upstream}`))))
81+
.catch(e => reject(e))
82+
}))
83+
84+
Promise.all(reqs)
85+
.then(() => res.end(JSON.stringify(value, null, 2)))
86+
.catch(e => res.status(400).end(`Cannot compare ${e.message}`))
7887
})
88+
.catch(e => res.status(400).end(`File not found or invalid`))
7989
})
8090
}

‎lib/schema.js‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,16 +28,17 @@ const fields = {
2828
}
2929

3030
const ruleSchema = Joi.object().keys({
31+
base: fields.branch.required(),
3132
upstream: fields.upstream.required(),
3233
autoMerge: fields.autoMerge.default(false),
33-
autoMergeHardReset: fields.autoMerge.default(false)
34+
autoMergeHardReset: fields.autoMerge.default(false),
35+
assignees: fields.assignees.default([]),
36+
reviewers: fields.assignees.default([])
3437
}).options({ stripUnknown: true }).required()
3538

3639
const schema = Joi.object().keys({
3740
version: fields.version.required(),
38-
rules: Joi.object().pattern(/[^\s:]+/, ruleSchema).required(),
39-
assignees: fields.assignees.default([]),
40-
reviewers: fields.assignees.default([]),
41+
rules: Joi.array().items(ruleSchema).min(1).unique().required(),
4142
label: fields.label.default('sync-up :arrow_up_down:')
4243
}).options({ stripUnknown: true }).required()
4344

‎lib/sync-up.js‎

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -18,20 +18,19 @@ module.exports = class SyncUp {
1818
async routineCheck () {
1919
this.logger.debug(`[${this.config.repoPath}] Config: ${JSON.stringify(this.config)}`)
2020

21-
const refs = Object.keys(this.config.rules)
22-
for (let i = 0; i < refs.length; i++) {
23-
const ref = refs[i]
24-
const c = this.config.rules[ref]
25-
26-
if (ref.toLowerCase() === c.upstream.toLowerCase().replace(`${this.config.owner.toLowerCase()}:`, '')) {
27-
this.logger.debug(`[${this.config.repoPath}] ${ref} is same as ${c.upstream}`)
28-
} else if (!(await this.hasDiff(ref, c.upstream))) {
29-
this.logger.info(`[${this.config.repoPath}] ${ref} is in sync with ${c.upstream}`)
30-
} else if (await this.hasOpenPR(ref)) {
31-
this.logger.info(`[${this.config.repoPath}] Already has PR from ${c.upstream} to ${ref}`)
21+
for (let i = 0; i < this.config.rules.length; i++) {
22+
const rule = this.config.rules[i]
23+
const { base, upstream, assignees, reviewers } = rule
24+
25+
if (base.toLowerCase() === upstream.toLowerCase().replace(`${this.config.owner.toLowerCase()}:`, '')) {
26+
this.logger.debug(`[${this.config.repoPath}] ${base} is same as ${upstream}`)
27+
} else if (!(await this.hasDiff(base, upstream))) {
28+
this.logger.info(`[${this.config.repoPath}] ${base} is in sync with ${upstream}`)
29+
} else if (await this.hasOpenPR(base)) {
30+
this.logger.info(`[${this.config.repoPath}] Already has PR from ${upstream} to ${base}`)
3231
} else {
33-
this.logger.info(`[${this.config.repoPath}] Creating PR from ${c.upstream} to ${ref}`)
34-
await this.createPR(ref, c.upstream)
32+
this.logger.info(`[${this.config.repoPath}] Creating PR from ${upstream} to ${base}`)
33+
await this.createPR(base, upstream, assignees, reviewers)
3534
}
3635
}
3736
}
@@ -41,22 +40,23 @@ module.exports = class SyncUp {
4140
const prNumber = incomingPR.number
4241
this.logger.debug(`[${this.config.repoPath}]#${prNumber} Checking auto merged pull request`)
4342

44-
const c = this.config.rules[incomingPR.base.ref]
43+
const rule = this.config.rules.filter(r =>
44+
r.base === incomingPR.base.ref &&
45+
(r.upstream === incomingPR.head.label || r.upstream === incomingPR.head.ref))[0]
4546

46-
if (c.autoMerge &&
47+
if (rule && rule.autoMerge &&
4748
incomingPR.state === 'open' &&
4849
incomingPR.user.login === 'sync-up[bot]' &&
4950
incomingPR.mergeable !== false
5051
) {
51-
const mergable = incomingPR.mergeable_state === 'clean' || await this.isMergeable(prNumber, { maxRetries: config.isMergableMaxRetries || undefined })
52+
const mergable = incomingPR.mergeable_state === 'clean' ||
53+
await this.isMergeable(prNumber, { maxRetries: config.isMergableMaxRetries || undefined })
5254
this.logger.debug(`[${this.config.repoPath}]#${prNumber} Mergability ${mergable}`)
53-
if (!mergable) {
54-
// Do nothing
55-
} else {
56-
await this.mergePR(prNumber, c.autoMergeMethod)
55+
if (mergable) {
56+
await this.mergePR(prNumber)
5757
this.logger.debug(`[${this.config.repoPath}]#${prNumber} Auto merged pull request`)
5858

59-
if (c.autoMergeHardReset) {
59+
if (rule.autoMergeHardReset) {
6060
this.logger.debug(`[${this.config.repoPath}]#${prNumber} Performing hard reset`)
6161
try {
6262
await this.hardResetCommit(incomingPR.base.ref, incomingPR.head.sha)
@@ -73,33 +73,33 @@ module.exports = class SyncUp {
7373
return false
7474
}
7575

76-
async hasDiff (ref, upstream) {
76+
async hasDiff (base, upstream) {
7777
const comparison = await this.github.repos.compareCommits({
7878
owner: this.config.owner,
7979
repo: this.config.repo,
8080
head: upstream,
81-
base: ref
81+
base
8282
})
8383
return comparison.data.total_commits > 0
8484
}
8585

86-
async hasOpenPR (ref) {
86+
async hasOpenPR (base) {
8787
const res = await this.github.search.issues({
88-
q: `repo:${this.config.repoPath} type:pr is:open base:${ref} author:app/sync-up`,
88+
q: `repo:${this.config.repoPath} type:pr is:open base:${base} author:app/sync-up`,
8989
per_page: 1, // Cannot be 0 because it will fallback to default: 30
9090
page: 1
9191
})
9292
return res.data.total_count > 0
9393
}
9494

95-
async createPR (ref, upstream) {
95+
async createPR (base, upstream, assignees, reviewers) {
9696
const createdPR = await this.github.pullRequests.create({
9797
owner: this.config.owner,
9898
repo: this.config.repo,
9999
head: upstream,
100-
base: ref,
100+
base,
101101
maintainer_can_modify: false,
102-
title: helper.getPRTitle(ref, upstream),
102+
title: helper.getPRTitle(base, upstream),
103103
body: helper.getPRBody(this.config.repoPath)
104104
})
105105

@@ -111,12 +111,12 @@ module.exports = class SyncUp {
111111
owner: this.config.owner,
112112
repo: this.config.repo,
113113
number: createdPR.data.number,
114-
assignees: this.config.assignees,
114+
assignees,
115115
labels: [this.config.label],
116116
body: helper.getPRBody(this.config.repoPath, prNumber)
117117
})
118118

119-
await this.addReviewers(prNumber, this.config.reviewers)
119+
await this.addReviewers(prNumber, reviewers)
120120

121121
this.logger.info(`[${this.config.repoPath}]#${prNumber} Updated pull request`)
122122
}

‎now.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
"alias": "sync-up.now.sh",
44
"type": "npm",
55
"env": {
6-
"APP_ID": "12711",
76
"NODE_ENV": "production",
8-
"LOG_LEVEL": "info"
7+
"LOG_LEVEL": "info",
8+
"APP_ID": "12711",
9+
"WEBHOOK_PATH": "/webhook"
910
},
1011
"scale": {
1112
"sfo1": {

‎package.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@
77
"repository": "https://github.com/wei/sync-up.git",
88
"scripts": {
99
"dev": "nodemon --exec \"npm start\"",
10-
"start": "PRIVATE_KEY=$(echo $PRIVATE_BASE64 | base64 -d) probot run ./index.js",
10+
"start": "probot run ./index.js",
11+
"now-start": "PRIVATE_KEY=$(echo $PRIVATE_BASE64 | base64 -d) npm start",
1112
"lint:fix": "standard --fix",
1213
"test": "standard && jest",
1314
"test:watch": "jest --watchAll --notify --notifyMode=change --coverage",
14-
"deploy": "now --public -e WEBHOOK_SECRET=$WEBHOOK_SECRET -e PRIVATE_BASE64=\"$PRIVATE_BASE64\" --token=$NOW_TOKEN && now alias --token=$NOW_TOKEN && now rm sync-up --safe -y --token=$NOW_TOKEN"
15+
"deploy": "now --public -e WEBHOOK_SECRET=$WEBHOOK_SECRET -e PRIVATE_BASE64=\"$PRIVATE_BASE64\" --token=$NOW_TOKEN && now alias --token=$NOW_TOKEN && now rm sync-up --safe -y --token=$NOW_TOKEN && now scale sync-up.now.sh sfo1 1 --token=$NOW_TOKEN"
1516
},
1617
"dependencies": {
1718
"joi": "^13.3.0",

0 commit comments

Comments
 (0)