Struct repo_icons::Readme

source ·
pub struct Readme {
    pub owner: String,
    pub repo: String,
    pub homepage: Option<Url>,
    pub private: bool,
    /* private fields */
}

Fields§

§owner: String§repo: String§homepage: Option<Url>§private: bool

Implementations§

Examples found in repository?
src/repo_icons.rs (line 55)
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
  pub async fn load(
    owner: &str,
    repo: &str,
    best_matches_only: bool,
  ) -> Result<Self, Box<dyn Error>> {
    let mut repo_icons = Vec::new();

    let readme = github_api::Readme::load(owner, repo).shared();

    let mut futures: Vec<Pin<Box<dyn Future<Output = Result<LoadedKind, Box<dyn Error>>>>>> = vec![
      async {
        // Check if the repo contains the owner's username, and load the user's avatar
        let docs = regex!("^(docs|documentation)$");
        let icon = if repo.to_lowercase().contains(&owner_name_lowercase(owner))
          || docs.is_match(&repo.to_lowercase()).unwrap()
        {
          RepoIcon::load_user_avatar(owner).await
        } else {
          None
        };

        Ok(LoadedKind::UserAvatar(icon))
      }
      .boxed_local(),
      // Try and find prefixed repos, and load icons for them on GitHub
      async {
        let repos = github_api::get_user_repos(owner).await?;

        Ok(LoadedKind::PrefixedRepo(
          join_all(
            repos
              .into_iter()
              .filter(|possibly_prefixed_repo| {
                possibly_prefixed_repo != &repo.to_lowercase()
                  && repo.to_lowercase().contains(possibly_prefixed_repo)
              })
              .map(async move |repo| {
                RepoIcons::load(owner, &repo, best_matches_only)
                  .await
                  .map(|icons| icons.0.into_vec())
                  .unwrap_or(Vec::new())
              }),
          )
          .await
          .into_iter()
          .flatten()
          .collect::<Vec<_>>()
          .try_into()
          .ok(),
        ))
      }
      .boxed_local(),
      async {
        let blob_icons = match github_api::get_blobs(owner, repo).await? {
          Some((is_icon_field, blobs)) => Some(
            try_join_all(
              blobs
                .into_iter()
                .map(|blob| RepoIcon::load_blob(blob, is_icon_field)),
            )
            .await?
            .try_into()
            .unwrap(),
          ),
          None => None,
        };

        Ok(LoadedKind::Blob(blob_icons))
      }
      .boxed_local(),
      async {
        let mut icons = Icons::new_with_blacklist(|url| is_blacklisted_homepage(url));

        let homepage = readme.clone().await?.homepage;

        if let Some(homepage) = &homepage {
          warn_err!(
            icons.load_website(homepage.clone()).await,
            "failed to load website {}",
            homepage
          );
        }

        Ok(LoadedKind::Homepage(
          icons
            .entries()
            .await
            .into_iter()
            .filter(|icon| !is_badge_url(&icon.url))
            .map(|icon| {
              RepoIcon::new(
                icon.url,
                (homepage.clone().unwrap(), icon.kind).into(),
                icon.info,
              )
            })
            .collect::<Vec<_>>()
            .try_into()
            .ok(),
        ))
      }
      .boxed_local(),
      // Try and extract images from the readme website, or directly in it
      async {
        let image = readme
          .clone()
          .await?
          .load_body()
          .await?
          .into_iter()
          .find(|image| image.in_primary_heading);

        let icon = match image {
          Some(image) => Some(
            RepoIcon::load_with_headers(image.src, image.headers, RepoIconKind::ReadmeImage)
              .await?,
          ),
          None => None,
        };

        Ok(LoadedKind::ReadmeImage(icon))
      }
      .boxed_local(),
    ];

    let mut previous_loads = Vec::new();
    let mut found_best_match = false;

    let mut error = Ok(());

    while !futures.is_empty() {
      let (loaded, index, _) = select_all(&mut futures).await;
      futures.remove(index);

      let loaded = match loaded {
        Err(err) => {
          error = Err(err);
          continue;
        }
        Ok(loaded) => loaded,
      };

      match &loaded {
        LoadedKind::Blob(blob_icons) => {
          if let Some(mut blob_icons) = blob_icons.clone() {
            for blob_icon in &mut blob_icons {
              blob_icon.set_repo_private(readme.clone().await?.private);

              if matches!(blob_icon.kind, RepoIconKind::IconField(_)) {
                found_best_match = true;
              }
            }

            repo_icons.extend(blob_icons);

            if previous_loads
              .iter()
              .any(|loaded| matches!(loaded, LoadedKind::UserAvatar(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Homepage(_)))
            {
              found_best_match = true;
            }
          }
        }

        LoadedKind::UserAvatar(user_avatar) => {
          if let Some(blob_kinds) = previous_loads.iter().find_map(|loaded| {
            if let LoadedKind::Blob(blob_icons) = loaded {
              Some(blob_icons.as_ref().map(|blob_icons| {
                blob_icons
                  .iter()
                  .map(|blob| blob.kind.clone())
                  .collect::<Vec<_>>()
              }))
            } else {
              None
            }
          }) {
            if let Some(blob_kinds) = blob_kinds {
              for blob_kind in blob_kinds {
                if matches!(blob_kind, RepoIconKind::RepoFile(_)) {
                  found_best_match = true;
                }
              }
            } else {
              found_best_match = true;
            }
          }

          if let Some(user_avatar) = user_avatar {
            repo_icons.push(user_avatar.clone());
          }
        }

        LoadedKind::ReadmeImage(readme_image) => {
          if let Some(readme_image) = readme_image {
            if previous_loads
              .iter()
              .any(|loaded| matches!(loaded, LoadedKind::UserAvatar(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Blob(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Homepage(_)))
            {
              found_best_match = true;
            }

            repo_icons.push(readme_image.clone());
          }
        }

        LoadedKind::PrefixedRepo(icons) => {
          if let Some(icons) = icons {
            repo_icons.extend(icons.clone());
          }
        }

        LoadedKind::Homepage(site_icons) => {
          if let Some(site_icons) = site_icons {
            repo_icons.extend(site_icons.clone());

            if site_icons.iter().any(|icon| {
              matches!(
                icon.kind,
                RepoIconKind::AppIcon { .. } | RepoIconKind::SiteFavicon { .. }
              )
            }) && previous_loads
              .iter()
              .any(|loaded| matches!(loaded, LoadedKind::UserAvatar(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Blob(_)))
            {
              found_best_match = true;
            }
          }
        }
      }

      previous_loads.push(loaded);

      repo_icons.sort_by(|a, b| a.info.cmp(&b.info));
      repo_icons.sort_by(|a, b| a.kind.cmp(&b.kind));

      if best_matches_only && found_best_match {
        break;
      }
    }

    error?;

    let repo_icons = repo_icons
      .into_iter()
      .unique_by(|icon| icon.url.clone())
      .collect::<Vec<_>>();

    let repo_icons: Vec1<RepoIcon> = repo_icons
      .try_into()
      .map_err(|_| "no icons found for repo")?;

    Ok(RepoIcons(repo_icons))
  }
Examples found in repository?
src/repo_icons.rs (line 155)
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
  pub async fn load(
    owner: &str,
    repo: &str,
    best_matches_only: bool,
  ) -> Result<Self, Box<dyn Error>> {
    let mut repo_icons = Vec::new();

    let readme = github_api::Readme::load(owner, repo).shared();

    let mut futures: Vec<Pin<Box<dyn Future<Output = Result<LoadedKind, Box<dyn Error>>>>>> = vec![
      async {
        // Check if the repo contains the owner's username, and load the user's avatar
        let docs = regex!("^(docs|documentation)$");
        let icon = if repo.to_lowercase().contains(&owner_name_lowercase(owner))
          || docs.is_match(&repo.to_lowercase()).unwrap()
        {
          RepoIcon::load_user_avatar(owner).await
        } else {
          None
        };

        Ok(LoadedKind::UserAvatar(icon))
      }
      .boxed_local(),
      // Try and find prefixed repos, and load icons for them on GitHub
      async {
        let repos = github_api::get_user_repos(owner).await?;

        Ok(LoadedKind::PrefixedRepo(
          join_all(
            repos
              .into_iter()
              .filter(|possibly_prefixed_repo| {
                possibly_prefixed_repo != &repo.to_lowercase()
                  && repo.to_lowercase().contains(possibly_prefixed_repo)
              })
              .map(async move |repo| {
                RepoIcons::load(owner, &repo, best_matches_only)
                  .await
                  .map(|icons| icons.0.into_vec())
                  .unwrap_or(Vec::new())
              }),
          )
          .await
          .into_iter()
          .flatten()
          .collect::<Vec<_>>()
          .try_into()
          .ok(),
        ))
      }
      .boxed_local(),
      async {
        let blob_icons = match github_api::get_blobs(owner, repo).await? {
          Some((is_icon_field, blobs)) => Some(
            try_join_all(
              blobs
                .into_iter()
                .map(|blob| RepoIcon::load_blob(blob, is_icon_field)),
            )
            .await?
            .try_into()
            .unwrap(),
          ),
          None => None,
        };

        Ok(LoadedKind::Blob(blob_icons))
      }
      .boxed_local(),
      async {
        let mut icons = Icons::new_with_blacklist(|url| is_blacklisted_homepage(url));

        let homepage = readme.clone().await?.homepage;

        if let Some(homepage) = &homepage {
          warn_err!(
            icons.load_website(homepage.clone()).await,
            "failed to load website {}",
            homepage
          );
        }

        Ok(LoadedKind::Homepage(
          icons
            .entries()
            .await
            .into_iter()
            .filter(|icon| !is_badge_url(&icon.url))
            .map(|icon| {
              RepoIcon::new(
                icon.url,
                (homepage.clone().unwrap(), icon.kind).into(),
                icon.info,
              )
            })
            .collect::<Vec<_>>()
            .try_into()
            .ok(),
        ))
      }
      .boxed_local(),
      // Try and extract images from the readme website, or directly in it
      async {
        let image = readme
          .clone()
          .await?
          .load_body()
          .await?
          .into_iter()
          .find(|image| image.in_primary_heading);

        let icon = match image {
          Some(image) => Some(
            RepoIcon::load_with_headers(image.src, image.headers, RepoIconKind::ReadmeImage)
              .await?,
          ),
          None => None,
        };

        Ok(LoadedKind::ReadmeImage(icon))
      }
      .boxed_local(),
    ];

    let mut previous_loads = Vec::new();
    let mut found_best_match = false;

    let mut error = Ok(());

    while !futures.is_empty() {
      let (loaded, index, _) = select_all(&mut futures).await;
      futures.remove(index);

      let loaded = match loaded {
        Err(err) => {
          error = Err(err);
          continue;
        }
        Ok(loaded) => loaded,
      };

      match &loaded {
        LoadedKind::Blob(blob_icons) => {
          if let Some(mut blob_icons) = blob_icons.clone() {
            for blob_icon in &mut blob_icons {
              blob_icon.set_repo_private(readme.clone().await?.private);

              if matches!(blob_icon.kind, RepoIconKind::IconField(_)) {
                found_best_match = true;
              }
            }

            repo_icons.extend(blob_icons);

            if previous_loads
              .iter()
              .any(|loaded| matches!(loaded, LoadedKind::UserAvatar(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Homepage(_)))
            {
              found_best_match = true;
            }
          }
        }

        LoadedKind::UserAvatar(user_avatar) => {
          if let Some(blob_kinds) = previous_loads.iter().find_map(|loaded| {
            if let LoadedKind::Blob(blob_icons) = loaded {
              Some(blob_icons.as_ref().map(|blob_icons| {
                blob_icons
                  .iter()
                  .map(|blob| blob.kind.clone())
                  .collect::<Vec<_>>()
              }))
            } else {
              None
            }
          }) {
            if let Some(blob_kinds) = blob_kinds {
              for blob_kind in blob_kinds {
                if matches!(blob_kind, RepoIconKind::RepoFile(_)) {
                  found_best_match = true;
                }
              }
            } else {
              found_best_match = true;
            }
          }

          if let Some(user_avatar) = user_avatar {
            repo_icons.push(user_avatar.clone());
          }
        }

        LoadedKind::ReadmeImage(readme_image) => {
          if let Some(readme_image) = readme_image {
            if previous_loads
              .iter()
              .any(|loaded| matches!(loaded, LoadedKind::UserAvatar(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Blob(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Homepage(_)))
            {
              found_best_match = true;
            }

            repo_icons.push(readme_image.clone());
          }
        }

        LoadedKind::PrefixedRepo(icons) => {
          if let Some(icons) = icons {
            repo_icons.extend(icons.clone());
          }
        }

        LoadedKind::Homepage(site_icons) => {
          if let Some(site_icons) = site_icons {
            repo_icons.extend(site_icons.clone());

            if site_icons.iter().any(|icon| {
              matches!(
                icon.kind,
                RepoIconKind::AppIcon { .. } | RepoIconKind::SiteFavicon { .. }
              )
            }) && previous_loads
              .iter()
              .any(|loaded| matches!(loaded, LoadedKind::UserAvatar(_)))
              && previous_loads
                .iter()
                .any(|loaded| matches!(loaded, LoadedKind::Blob(_)))
            {
              found_best_match = true;
            }
          }
        }
      }

      previous_loads.push(loaded);

      repo_icons.sort_by(|a, b| a.info.cmp(&b.info));
      repo_icons.sort_by(|a, b| a.kind.cmp(&b.kind));

      if best_matches_only && found_best_match {
        break;
      }
    }

    error?;

    let repo_icons = repo_icons
      .into_iter()
      .unique_by(|icon| icon.url.clone())
      .collect::<Vec<_>>();

    let repo_icons: Vec1<RepoIcon> = repo_icons
      .try_into()
      .map_err(|_| "no icons found for repo")?;

    Ok(RepoIcons(repo_icons))
  }

Check if a given url is a project link.

Examples found in repository?
src/github_api/readme/readme_image.rs (line 94)
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
  pub async fn get(
    readme: &Readme,
    elem_ref: &ElementRef<'_>,
    primary_heading: &mut PrimaryHeading<'_>,
  ) -> Option<Self> {
    let elem = elem_ref.value();

    let src = elem
      .attr("data-canonical-src")
      .or(elem.attr("src"))
      .and_then(|src| readme.qualify_url(src).ok())
      .unwrap();

    let alt = elem
      .attr("alt")
      .map(|alt| alt.to_lowercase())
      .unwrap_or(String::new());

    if is_badge_url(&src) || is_badge_text(&alt) {
      return None;
    }

    let cdn_src = elem
      .attr("data-canonical-src")
      .and(elem.attr("src"))
      .and_then(|src| readme.qualify_url(src).ok());

    let mut is_align_center = false;
    let mut links_to = None;
    for elem_ref in elem_ref.ancestors().map(ElementRef::wrap).flatten() {
      let element = elem_ref.value();

      if element.attr("align") == Some("center") {
        is_align_center = true;
      }

      if element.name() == "a" && links_to.is_none() {
        links_to = match element
          .attr("href")
          .and_then(|href| readme.qualify_url(href).ok())
        {
          Some(href) => {
            // if the img points to the same url as the link
            // then its a default url generated by github
            let mut img_blob_url = src.clone();
            img_blob_url.set_path(&src.path().replacen("/raw/", "/blob/", 1));
            if href != img_blob_url {
              readme.is_link_to_project(&href).await
            } else {
              None
            }
          }
          None => None,
        };
      }
    }

    let branch_and_path = readme.get_branch_and_path(&src).await;
    let keyword_mentions = {
      let mut mentions = HashSet::new();

      let mut path = &src.path().to_lowercase();
      if let Some((_, file_path)) = &branch_and_path {
        path = file_path;
      }

      if path.contains("logo") || alt.contains("logo") {
        mentions.insert(KeywordMention::Logo);
      }

      if path.contains("banner") || alt.contains("banner") {
        mentions.insert(KeywordMention::Banner);
      }

      if path.contains(&readme.repo) || alt.contains(&readme.repo) {
        mentions.insert(KeywordMention::RepoName);
      };
      mentions
    };

    let mut headers = HashMap::new();

    let src = cdn_src.unwrap_or({
      if let Some((branch, path)) = &branch_and_path {
        if readme.private {
          headers.insert(
            "Authorization".to_string(),
            format!("Bearer {}", get_token().unwrap()).to_string(),
          );
        }

        Url::parse(&format!(
          "https://raw.githubusercontent.com/{}/{}/{}/{}",
          readme.owner, readme.repo, branch, path
        ))
        .unwrap()
      } else {
        src
      }
    });

    Some(ReadmeImage {
      src,
      headers,
      in_primary_heading: primary_heading.contains(elem_ref),
      edge_of_primary_heading: false,
      keyword_mentions,
      sourced_from_repo: branch_and_path.is_some(),
      links_to,
      is_align_center,
      has_size_attrs: elem.attr("width").or(elem.attr("height")).is_some(),
    })
  }

Check if a given url points to a file located inside the repo.

Examples found in repository?
src/github_api/readme/mod.rs (line 183)
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
  pub async fn is_link_to_project(&self, url: &Url) -> Option<ProjectLink> {
    let domain = url.domain()?.to_lowercase();

    // check for github pages
    let re = regex!(r"^([^.])+\.github\.(com|io)$");
    if let Some(res) = re.captures(&domain).unwrap() {
      let user = &res[1];

      // USERNAME.github.io
      if let Some(repo_res) = re.captures(&domain).unwrap() {
        if &repo_res[1] == user {
          return Some(ProjectLink::Website);
        }
      }

      // USERNAME.github.io/REPO
      if let Some(res) = regex!("^/([^/]+)").captures(url.path()).unwrap() {
        let repo = &res[1];
        if self.is_same_repo_as(user, repo).await {
          return Some(ProjectLink::Website);
        }
      }
    }

    if self
      .homepage
      .as_ref()
      .and_then(|u| u.domain().map(|d| d.to_lowercase()))
      .map(|d| domain == d)
      .unwrap_or(false)
    {
      return Some(ProjectLink::Website);
    }

    if self.get_branch_and_path(url).await.is_some() {
      return Some(ProjectLink::Repo);
    };

    None
  }
More examples
Hide additional examples
src/github_api/readme/readme_image.rs (line 104)
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
  pub async fn get(
    readme: &Readme,
    elem_ref: &ElementRef<'_>,
    primary_heading: &mut PrimaryHeading<'_>,
  ) -> Option<Self> {
    let elem = elem_ref.value();

    let src = elem
      .attr("data-canonical-src")
      .or(elem.attr("src"))
      .and_then(|src| readme.qualify_url(src).ok())
      .unwrap();

    let alt = elem
      .attr("alt")
      .map(|alt| alt.to_lowercase())
      .unwrap_or(String::new());

    if is_badge_url(&src) || is_badge_text(&alt) {
      return None;
    }

    let cdn_src = elem
      .attr("data-canonical-src")
      .and(elem.attr("src"))
      .and_then(|src| readme.qualify_url(src).ok());

    let mut is_align_center = false;
    let mut links_to = None;
    for elem_ref in elem_ref.ancestors().map(ElementRef::wrap).flatten() {
      let element = elem_ref.value();

      if element.attr("align") == Some("center") {
        is_align_center = true;
      }

      if element.name() == "a" && links_to.is_none() {
        links_to = match element
          .attr("href")
          .and_then(|href| readme.qualify_url(href).ok())
        {
          Some(href) => {
            // if the img points to the same url as the link
            // then its a default url generated by github
            let mut img_blob_url = src.clone();
            img_blob_url.set_path(&src.path().replacen("/raw/", "/blob/", 1));
            if href != img_blob_url {
              readme.is_link_to_project(&href).await
            } else {
              None
            }
          }
          None => None,
        };
      }
    }

    let branch_and_path = readme.get_branch_and_path(&src).await;
    let keyword_mentions = {
      let mut mentions = HashSet::new();

      let mut path = &src.path().to_lowercase();
      if let Some((_, file_path)) = &branch_and_path {
        path = file_path;
      }

      if path.contains("logo") || alt.contains("logo") {
        mentions.insert(KeywordMention::Logo);
      }

      if path.contains("banner") || alt.contains("banner") {
        mentions.insert(KeywordMention::Banner);
      }

      if path.contains(&readme.repo) || alt.contains(&readme.repo) {
        mentions.insert(KeywordMention::RepoName);
      };
      mentions
    };

    let mut headers = HashMap::new();

    let src = cdn_src.unwrap_or({
      if let Some((branch, path)) = &branch_and_path {
        if readme.private {
          headers.insert(
            "Authorization".to_string(),
            format!("Bearer {}", get_token().unwrap()).to_string(),
          );
        }

        Url::parse(&format!(
          "https://raw.githubusercontent.com/{}/{}/{}/{}",
          readme.owner, readme.repo, branch, path
        ))
        .unwrap()
      } else {
        src
      }
    });

    Some(ReadmeImage {
      src,
      headers,
      in_primary_heading: primary_heading.contains(elem_ref),
      edge_of_primary_heading: false,
      keyword_mentions,
      sourced_from_repo: branch_and_path.is_some(),
      links_to,
      is_align_center,
      has_size_attrs: elem.attr("width").or(elem.attr("height")).is_some(),
    })
  }
Examples found in repository?
src/github_api/readme/readme_image.rs (line 57)
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
  pub async fn get(
    readme: &Readme,
    elem_ref: &ElementRef<'_>,
    primary_heading: &mut PrimaryHeading<'_>,
  ) -> Option<Self> {
    let elem = elem_ref.value();

    let src = elem
      .attr("data-canonical-src")
      .or(elem.attr("src"))
      .and_then(|src| readme.qualify_url(src).ok())
      .unwrap();

    let alt = elem
      .attr("alt")
      .map(|alt| alt.to_lowercase())
      .unwrap_or(String::new());

    if is_badge_url(&src) || is_badge_text(&alt) {
      return None;
    }

    let cdn_src = elem
      .attr("data-canonical-src")
      .and(elem.attr("src"))
      .and_then(|src| readme.qualify_url(src).ok());

    let mut is_align_center = false;
    let mut links_to = None;
    for elem_ref in elem_ref.ancestors().map(ElementRef::wrap).flatten() {
      let element = elem_ref.value();

      if element.attr("align") == Some("center") {
        is_align_center = true;
      }

      if element.name() == "a" && links_to.is_none() {
        links_to = match element
          .attr("href")
          .and_then(|href| readme.qualify_url(href).ok())
        {
          Some(href) => {
            // if the img points to the same url as the link
            // then its a default url generated by github
            let mut img_blob_url = src.clone();
            img_blob_url.set_path(&src.path().replacen("/raw/", "/blob/", 1));
            if href != img_blob_url {
              readme.is_link_to_project(&href).await
            } else {
              None
            }
          }
          None => None,
        };
      }
    }

    let branch_and_path = readme.get_branch_and_path(&src).await;
    let keyword_mentions = {
      let mut mentions = HashSet::new();

      let mut path = &src.path().to_lowercase();
      if let Some((_, file_path)) = &branch_and_path {
        path = file_path;
      }

      if path.contains("logo") || alt.contains("logo") {
        mentions.insert(KeywordMention::Logo);
      }

      if path.contains("banner") || alt.contains("banner") {
        mentions.insert(KeywordMention::Banner);
      }

      if path.contains(&readme.repo) || alt.contains(&readme.repo) {
        mentions.insert(KeywordMention::RepoName);
      };
      mentions
    };

    let mut headers = HashMap::new();

    let src = cdn_src.unwrap_or({
      if let Some((branch, path)) = &branch_and_path {
        if readme.private {
          headers.insert(
            "Authorization".to_string(),
            format!("Bearer {}", get_token().unwrap()).to_string(),
          );
        }

        Url::parse(&format!(
          "https://raw.githubusercontent.com/{}/{}/{}/{}",
          readme.owner, readme.repo, branch, path
        ))
        .unwrap()
      } else {
        src
      }
    });

    Some(ReadmeImage {
      src,
      headers,
      in_primary_heading: primary_heading.contains(elem_ref),
      edge_of_primary_heading: false,
      keyword_mentions,
      sourced_from_repo: branch_and_path.is_some(),
      links_to,
      is_align_center,
      has_size_attrs: elem.attr("width").or(elem.attr("height")).is_some(),
    })
  }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Instruments this type with the current Span, returning an Instrumented wrapper. Read more

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more