1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
use super::{
    finder::parse::parse_owner_and_repo_from_config,
    parser::{issue::*, FileTodoLocation, IssueMap},
};
use hyper::{
    body::{Body, HttpBody},
    Client, Request, Response,
};
use hyper_tls::HttpsConnector;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::{json, Value};
use std::process::Command;


#[derive(Deserialize)]
struct GitHubConfig {
    // Label to use for filtering TODO issues
    issue_label: String,
    // Github token
    auth_token: String,
    // Where do we search for TODOs
    _search_in_directory: Option<String>,
    // The repo owner
    owner: String,
    // The repo name
    repo: String,
    // The current checkout hash
    checkout_hash: String,
    // The root project directory
    root_project_dir: String,
}


#[derive(Debug, Serialize, Deserialize)]
pub struct GitHubLabel {
    pub id: u32,
    pub name: String,
    pub description: Option<String>,
}


#[derive(Debug, Serialize, Deserialize)]
pub struct GitHubAssignee {
    pub login: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GitHubUser {
    pub login: String,
}


#[derive(Debug, Serialize, Deserialize)]
pub struct GitHubIssue {
    pub id: u32,
    pub number: u32,
    pub title: String,
    pub body: String,
    pub state: String,
    pub labels: Vec<GitHubLabel>,
    pub assignees: Vec<GitHubAssignee>,
    pub user: GitHubUser,
}


pub struct GitHubPatch {
    pub create: IssueMap<(), FileTodoLocation>,
    pub edit: IssueMap<u32, FileTodoLocation>,
    pub delete: Vec<u32>,
}


pub fn github_issues_url(owner: &str, repo: &str) -> String {
    format!("https://api.github.com/repos/{}/{}/issues", owner, repo)
}


pub fn github_issues_update_url(owner: &str, repo: &str, id: u32) -> String {
    format!(
        "https://api.github.com/repos/{}/{}/issues/{}",
        owner, repo, id
    )
}


/// git config --get remote.origin.url
pub fn git_origin() -> Result<String, String> {
    let output = Command::new("git")
        .arg("config")
        .arg("--get")
        .arg("remote.origin.url")
        .output()
        .map_err(|e| format!("could not determine the git origin: {}", e))?;

    if !output.status.success() {
        let output = String::from_utf8_lossy(&output.stderr).to_string();
        return Err(format!("git config --get remote.origin.url: '{}'", output));
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}


/// git rev-parse HEAD
pub fn git_hash() -> Result<String, String> {
    let output = Command::new("git")
        .arg("rev-parse")
        .arg("HEAD")
        .output()
        .map_err(|e| format!("could not run git rev-parse HEAD: {}", e))?;

    if !output.status.success() {
        return Err("git rev-parse HEAD erred".into());
    }

    let s: String = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(s)
}


async fn get_github_issues(
    cfg: &GitHubConfig,
) -> Result<IssueMap<u32, GitHubTodoLocation>, String> {
    let url = github_issues_url(&cfg.owner, &cfg.repo);
    println!("  {}", url);
    let req = github_req(
        cfg,
        "GET",
        &url,
        json!({
          "labels": vec![&cfg.issue_label],
          "state": "open"
        }),
    )?;

    let https = HttpsConnector::new();
    let client = Client::builder().build::<_, hyper::Body>(https);

    let res = client
        .request(req)
        .await
        .map_err(|e| format!("error fetching github issues: {}", e))?;
    let github_issues: Vec<GitHubIssue> = get_json_response(res).await?;
    let mut issues = IssueMap::new_github_todos();
    for issue in github_issues.iter() {
        issues.add_issue(issue);
    }

    Ok(issues)
}


fn github_req<T: Serialize>(
    cfg: &GitHubConfig,
    method: &str,
    uri: &str,
    body: T,
) -> Result<Request<Body>, String> {
    let json_data = serde_json::to_string(&body)
        .map_err(|e| format!("could not serialize request body: {}", e))?;
    Request::builder()
        .method(method)
        .uri(uri)
        .header("User-Agent", &cfg.owner)
        .header("Accept", "application/json")
        .header("Authorization", format!("token {}", &cfg.auth_token))
        .body(json_data.into())
        .map_err(|e| format!("error building github request: {} {}", uri, e))
}


async fn get_json_response<T: DeserializeOwned>(mut res: Response<Body>) -> Result<T, String> {
    //println!("Response: {}", res.status());
    //println!("Headers: {:#?}\n", res.headers());

    // Stream the body, buffering each chunk to a string as we get it
    let mut chunks: Vec<String> = vec![];
    while let Some(next) = res.data().await {
        let chunk = next.map_err(|e| format!("error getting next chunk: {}", e))?;
        let chunk = String::from_utf8_lossy(&chunk).to_string();
        chunks.push(chunk);
    }
    let json_string = chunks.concat();
    serde_json::from_str::<T>(&json_string).map_err(|e| {
        format!(
            "could not deserialize github response: {}\nbody: {}",
            e, json_string
        )
    })
}


async fn apply_patch(cfg: &GitHubConfig, patch: GitHubPatch) -> Result<(), String> {
    let https = HttpsConnector::new();
    let client = Client::builder().build::<_, hyper::Body>(https);
    let url = github_issues_url(&cfg.owner, &cfg.repo);

    // Create
    println!("creating {} issues", patch.create.todos.len());
    for (_, issue) in patch.create.todos.iter() {
        let req = github_req(
            &cfg,
            "POST",
            &url,
            json!({
              "title": issue.head.title,
              "body": issue.body.to_github_string(
                &cfg.root_project_dir,
                &cfg.owner,
                &cfg.repo,
                &cfg.checkout_hash
              )?,
              "assignees": issue.head.assignees,
              "labels": vec![&cfg.issue_label]
            }),
        )?;
        let res: Response<Body> = client
            .request(req)
            .await
            .map_err(|e| format!("error creating github issue: {}", e))?;

        let _val: Value = get_json_response(res).await?;
        println!("created '{}':", issue.head.title);
        //println!("{:#?}", val);
    }

    // Edit
    println!("editing {} issues", patch.edit.todos.len());
    for (_, issue) in patch.edit.todos.iter() {
        println!("editing '{}'", issue.head.title);
        let id = issue.head.external_id;
        let body = issue
            .body
            .to_github_string(
                &cfg.root_project_dir,
                &cfg.owner,
                &cfg.repo,
                &cfg.checkout_hash,
            )
            .map_err(|e| format!("could not convert issue body to description: {}", e))?;
        let print_body = body
            .lines()
            .map(|s| vec!["  ".into(), s].concat())
            .collect::<Vec<_>>()
            .join("\n");
        println!("{}", print_body);

        let req = github_req(
            &cfg,
            "PATCH",
            &github_issues_update_url(&cfg.owner, &cfg.repo, id),
            json!({
              "title": issue.head.title,
              "body": body,
              "assignees": issue.head.assignees,
              "labels": vec![&cfg.issue_label]
            }),
        )?;
        let res: Response<Body> = client
            .request(req)
            .await
            .map_err(|e| format!("error editing github issue: {}", e))?;

        let _: Value = get_json_response(res).await?;
    }

    // Delete
    println!("deleting {} issues", patch.delete.len());
    for id in patch.delete.iter() {
        let req = github_req(
            &cfg,
            "PATCH",
            &github_issues_update_url(&cfg.owner, &cfg.repo, *id),
            json!({"state":"closed"}),
        )?;
        let res = client
            .request(req)
            .await
            .map_err(|e| format!("error closing github issue: {}", e))?;

        let json: Value = get_json_response(res).await?;
        let title = json
            .as_object()
            .map(|obj| obj.get("title").map(|s| s.as_str()).flatten())
            .flatten();
        if let Some(title) = title {
            println!("closed '{}'", title);
        }
    }

    Ok(())
}


pub async fn run_ts_github(
    auth_token: String,
    issue_label: String,
    cwd: String,
    excludes: &Vec<String>,
) -> Result<(), String> {
    //let path = Path::new(config_path_str);
    //let mut file: File = File::open(path).expect("could not open config file");
    //let mut contents = String::new();
    //file
    //  .read_to_string(&mut contents)
    //  .map_err(|e| format!("could not read config file {:#?}", e))?;

    //let config: ConfigFile = serde_yaml::from_str(&contents)
    //  .map_err(|e| format!("could not read config: {}", e))?;

    let origin = git_origin()?;
    println!("origin: {}", origin);
    let (owner, repo) = parse_owner_and_repo_from_config(&origin)
        .map_err(|_| "could not parse owner/repo from git config".to_string())?
        .1;
    println!("owner: '{}', repo: '{}'", owner, repo);
    let checkout_hash = git_hash()?;
    let local_issues = IssueMap::from_files_in_directory(&cwd, excludes).unwrap();
    let num_issues = local_issues.distinct_len();
    if num_issues > 0 {
        println!("Found {} distinct local TODOs", num_issues);
    }

    // Find the issues at the issue provider
    let cfg = GitHubConfig {
        issue_label,
        auth_token,
        _search_in_directory: None,
        owner: owner.into(),
        repo: repo.into(),
        checkout_hash,
        root_project_dir: cwd,
    };

    println!("Getting remote issues for {}/{}", owner, repo);
    let remote_issues = get_github_issues(&cfg).await?;

    let patch = remote_issues.prepare_patch(local_issues);

    println!("Patching remote issues");
    apply_patch(&cfg, patch).await?;

    Ok(())
}