Skip to content

Commit 36d4261

Browse files
author
Miqueas Martinez
committed
Revert "Removed C#, Python and Ruby examples"
This reverts commit df94787.
1 parent 4a9a4e9 commit 36d4261

File tree

3 files changed

+387
-0
lines changed

3 files changed

+387
-0
lines changed

Github.cs

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
using System;
2+
using System.Net;
3+
using Mono.Options;
4+
using Newtonsoft.Json.Linq;
5+
using System.Collections.Generic;
6+
using System.Text.RegularExpressions;
7+
8+
namespace Gth {
9+
public struct UserItem {
10+
public int Count;
11+
public string[] Arr;
12+
13+
public UserItem(int count) {
14+
Count = count;
15+
Arr = new string[count];
16+
}
17+
}
18+
19+
public class User {
20+
private const string API_USERS_URL = "https://api.github.com/users/";
21+
private const string USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36";
22+
private Regex fetch_patt = new Regex( "(repos|gists|followers|following)" );
23+
private string url;
24+
private JObject json;
25+
26+
public string Name;
27+
public string Bio;
28+
public string Link;
29+
public UserItem Repos;
30+
public UserItem Gists;
31+
public UserItem Followers;
32+
public UserItem Following;
33+
34+
public User(string name) {
35+
this.url = API_USERS_URL + name;
36+
37+
var client = new WebClient();
38+
client.Headers.Add("user-agent", USER_AGENT);
39+
40+
var res = client.DownloadString(this.url);
41+
json = JObject.Parse(res);
42+
43+
this.Name = json.Value<string>("name");
44+
this.Bio = json.Value<string>("bio");
45+
this.Link = json.Value<string>("html_url");
46+
47+
this.Repos = new UserItem(json.Value<int>("public_repos"));
48+
this.Gists = new UserItem(json.Value<int>("public_gists"));
49+
this.Followers = new UserItem(json.Value<int>("followers"));
50+
this.Following = new UserItem(json.Value<int>("following"));
51+
}
52+
53+
public void Fetch(string thing) {
54+
if (!fetch_patt.Match(thing).Success) {
55+
Console.WriteLine($"Unsupported endpoint: {thing}");
56+
return;
57+
}
58+
59+
var url = this.url + "/" + thing;
60+
var client = new WebClient();
61+
client.Headers.Add("user-agent", USER_AGENT);
62+
63+
var res = client.DownloadString(url);
64+
var arr = JArray.Parse(res);
65+
66+
if (thing == "repos") {
67+
for (int i = 0; i < arr.Count; i++)
68+
this.Repos.Arr[i] = arr[i].Value<string>("name");
69+
} else if (thing == "gists") {
70+
for (int i = 0; i < arr.Count; i++)
71+
this.Gists.Arr[i] = arr[i].Value<string>("description");
72+
} else if (thing == "followers") {
73+
for (int i = 0; i < arr.Count; i++)
74+
this.Followers.Arr[i] = arr[i].Value<string>("login");
75+
} else if (thing == "following") {
76+
for (int i = 0; i < arr.Count; i++)
77+
this.Following.Arr[i] = arr[i].Value<string>("login");
78+
}
79+
}
80+
}
81+
}
82+
83+
public class App {
84+
public static bool followers = false;
85+
public static bool following = false;
86+
public static bool repos = false;
87+
public static bool gists = false;
88+
89+
public static OptionSet opts = new OptionSet {
90+
{ "f|followers", "Shows user followers", f => followers = f != null },
91+
{ "F|following", "Shows user following", F => following = F != null },
92+
{ "r|repos", "Shows user repos", r => repos = r != null },
93+
{ "g|gists", "Shows user gists", g => gists = g != null }
94+
};
95+
96+
public static void Main(string[] argv) {
97+
List<string> args = opts.Parse(argv);
98+
99+
if (!(args.Count > 0)) {
100+
Console.WriteLine("No arguments");
101+
return;
102+
} else {
103+
foreach (string name in args) {
104+
var user = new Gth.User(name);
105+
106+
Console.WriteLine($"Name: {user.Name}");
107+
Console.WriteLine($"Bio: {user.Bio}");
108+
Console.WriteLine($"Link: {user.Link}");
109+
110+
Console.WriteLine($"Repos: {user.Repos.Count}");
111+
if (repos) {
112+
user.Fetch("repos");
113+
114+
for (var i = 0; i < user.Repos.Arr.Length; i++)
115+
Console.WriteLine($"| {i + 1}. {user.Repos.Arr[i]}");
116+
}
117+
118+
Console.WriteLine($"Gists: {user.Gists.Count}");
119+
if (gists) {
120+
user.Fetch("gists");
121+
122+
for (var i = 0; i < user.Gists.Arr.Length; i++)
123+
Console.WriteLine($"| {i + 1}. {user.Gists.Arr[i]}");
124+
}
125+
126+
Console.WriteLine($"Followers: {user.Followers.Count}");
127+
if (followers) {
128+
user.Fetch("followers");
129+
130+
for (var i = 0; i < user.Followers.Arr.Length; i++)
131+
Console.WriteLine($"| @{user.Followers.Arr[i]}");
132+
}
133+
134+
Console.WriteLine($"Following: {user.Following.Count}");
135+
if (following) {
136+
user.Fetch("following");
137+
138+
for (var i = 0; i < user.Following.Arr.Length; i++)
139+
Console.WriteLine($"| @{user.Following.Arr[i]}");
140+
}
141+
142+
Console.Write("\n");
143+
}
144+
}
145+
}
146+
}

Github.py

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import json
2+
import argparse
3+
import re
4+
from http import client
5+
6+
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36"
7+
API_HOST = "api.github.com"
8+
API_PATH = "/users/"
9+
10+
class GithubUser:
11+
def __init__(self, username: str):
12+
self.url = API_PATH + username
13+
14+
conn = client.HTTPSConnection(API_HOST)
15+
conn.request("GET", self.url, headers = { "User-Agent": USER_AGENT })
16+
17+
res = conn.getresponse()
18+
self.json = json.loads(res.read())
19+
20+
self.name = self.json["name"]
21+
self.bio = self.json["bio"]
22+
self.link = self.json["html_url"]
23+
24+
self.repos = { "count": self.json["public_repos"], "arr": [] }
25+
self.gists = { "count": self.json["public_gists"], "arr": [] }
26+
self.followers = { "count": self.json["followers"], "arr": [] }
27+
self.following = { "count": self.json["following"], "arr": [] }
28+
29+
res.close()
30+
conn.close()
31+
32+
def fetch(self, thing: str):
33+
assert (re.match(r'(repos|gists|followers|following)', thing) is not None), f"Unsupported endpoint: {thing}"
34+
35+
url = self.url + '/' + thing
36+
conn = client.HTTPSConnection(API_HOST)
37+
conn.request("GET", url, headers = { "User-Agent": USER_AGENT })
38+
39+
res = conn.getresponse()
40+
arr = json.loads(res.read())
41+
42+
if thing == "repos":
43+
for obj in arr:
44+
self.repos["arr"].append(obj["name"])
45+
46+
elif thing == "gists":
47+
for obj in arr:
48+
self.gists["arr"].append(obj["description"])
49+
50+
elif thing == "followers":
51+
for obj in arr:
52+
self.followers["arr"].append(obj["login"])
53+
54+
elif thing == "following":
55+
for obj in arr:
56+
self.following["arr"].append(obj["login"])
57+
58+
parser = argparse.ArgumentParser(
59+
usage = "Github.py [OPTIONS] usernames",
60+
description = "Commandline app demostrating the Github REST API",
61+
epilog = "https://github.com/Miqueas/Github-REST-API-Example"
62+
)
63+
64+
parser.add_argument("usernames", nargs = '+')
65+
parser.add_argument("-f", "--followers", action = "store_true", default = False)
66+
parser.add_argument("-F", "--following", action = "store_true", default = False)
67+
parser.add_argument("-r", "--repos", action = "store_true", default = False)
68+
parser.add_argument("-g", "--gists", action = "store_true", default = False)
69+
70+
args = parser.parse_args()
71+
72+
for name in args.usernames:
73+
user = GithubUser(name)
74+
75+
print(f"Name: {user.name}")
76+
print(f"Bio: {user.bio}")
77+
print(f"Link: {user.link}")
78+
79+
print(f"Repos: {user.repos['count']}")
80+
if args.repos:
81+
user.fetch("repos")
82+
83+
for i in range(len(user.repos['arr'])):
84+
print(f"| {i + 1}. {user.repos['arr'][i]}")
85+
86+
print(f"Gists: {user.gists['count']}")
87+
if args.gists:
88+
user.fetch("gists")
89+
90+
for i in range(len(user.gists["arr"])):
91+
print(f"| {i + 1}. {user.gists['arr'][i]}")
92+
93+
print(f"Followers: {user.followers['count']}")
94+
if args.followers:
95+
user.fetch("followers")
96+
97+
for i in range(len(user.followers["arr"])):
98+
print(f"| @{user.followers['arr'][i]}")
99+
100+
print(f"Following: {user.following['count']}")
101+
if args.following:
102+
user.fetch("following")
103+
104+
for i in range(len(user.following["arr"])):
105+
print(f"| @{user.following['arr'][i]}")
106+
107+
print()

Github.rb

Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
require 'net/http'
2+
require 'optparse'
3+
require 'ostruct'
4+
require 'json'
5+
6+
err = OptionParser::ParseError.new('see -h or --help for details')
7+
err.reason = 'No arguments'
8+
raise err if ARGV.empty?
9+
10+
BASE_URL = 'https://api.github.com/users/'
11+
12+
opts = { followers: false, following: false, repos: false, gists: false }
13+
14+
OptionParser.new do |opt|
15+
opt.banner = "Usage: Github [options] <usernames...>"
16+
opt.on('-f', '--followers', 'Shows user followers') { opts[:followers] = true }
17+
opt.on('-F', '--following', 'Shows user following') { opts[:following] = true }
18+
opt.on('-r', '--repos', 'Shows user repos') { opts[:repos] = true }
19+
opt.on('-g', '--gists', 'Shows user gists') { opts[:gists] = true }
20+
end.parse!
21+
22+
class GithubUser
23+
private
24+
attr_accessor :url, :json
25+
26+
public
27+
attr_accessor :name, :bio, :link
28+
attr_accessor :repos, :gists, :followers, :following
29+
30+
def initialize(username)
31+
type_err = TypeError.new("Bad argument for 'new'. String expected, got #{username.class}")
32+
raise type_err unless username.is_a? String
33+
34+
@url = URI(BASE_URL + username)
35+
36+
begin
37+
res = Net::HTTP.get(@url)
38+
@json = JSON.parse(res)
39+
rescue => err
40+
puts("Something went wrong! Here's some details:")
41+
puts(err.message)
42+
end
43+
44+
@name = @json['name'] || ''
45+
@bio = @json['bio'] || ''
46+
@link = @json['html_url'] || ''
47+
48+
@repos = { count: @json['public_repos'] || 0, arr: [] }
49+
@gists = { count: @json['public_gists'] || 0, arr: [] }
50+
@followers = { count: @json['followers'] || 0, arr: [] }
51+
@following = { count: @json['following'] || 0, arr: [] }
52+
end
53+
54+
def fetch(thing)
55+
type_err = TypeError.new("Bad argument for 'Fetch'. String expected, got #{thing.class}")
56+
raise type_err unless thing.is_a? String
57+
58+
begin
59+
url = URI(@url.to_s() + '/' + thing)
60+
res = Net::HTTP.get(url)
61+
arr = JSON.parse(res)
62+
rescue => err
63+
puts("Something's went wrong! Here's some details:")
64+
puts(err.message)
65+
end
66+
67+
case thing
68+
when 'repos'
69+
for val in arr do
70+
@repos[:arr].push(val['name'])
71+
end
72+
when 'gists'
73+
for val in arr do
74+
@gists[:arr].push(val['description'])
75+
end
76+
when 'followers'
77+
for val in arr do
78+
@followers[:arr].push('@' + val['login'])
79+
end
80+
when 'following'
81+
for val in arr do
82+
@following[:arr].push('@' + val['login'])
83+
end
84+
else
85+
puts("Unsupported endpoint: #{thing}")
86+
end
87+
end
88+
end
89+
90+
for arg in ARGV
91+
user = GithubUser.new(arg)
92+
93+
puts("Name: #{user.name}")
94+
puts("Bio: #{user.bio}")
95+
puts("Link: #{user.link}")
96+
97+
puts("Public repos: #{user.repos[:count]}")
98+
if opts[:repos]
99+
user.fetch('repos')
100+
101+
for i in 0 ... user.repos[:arr].size
102+
puts("| #{i + 1} #{user.repos[:arr][i]}")
103+
end
104+
end
105+
106+
puts("Public gists: #{user.gists[:count]}")
107+
if opts[:gists]
108+
user.fetch('gists')
109+
110+
for i in 0 ... user.gists[:arr].size
111+
puts("| #{i + 1}. #{user.gists[:arr][i]}")
112+
end
113+
end
114+
115+
puts("Followers: #{user.followers[:count]}")
116+
if opts[:followers]
117+
user.fetch('followers')
118+
119+
for v in user.followers[:arr]
120+
puts("| #{user.followers[:arr].index(v) + 1}. #{v}")
121+
end
122+
end
123+
124+
puts("Following: #{user.following[:count]}")
125+
if opts[:following]
126+
user.fetch('following')
127+
128+
for v in user.following[:arr]
129+
puts("| #{user.following[:arr].index(v) + 1}. #{v}")
130+
end
131+
end
132+
133+
print("\n")
134+
end

0 commit comments

Comments
 (0)